0

Pythonを学び、ユーザーがテキストの行を変更できるようにするスクリプトを書こうとしているだけです。何らかの理由で、置換する行を入力するようにユーザーに求めると、このエラーが発生します。

トレースバック(最後の最後の呼び出し):ファイル "textedit.py"、10行目、f.write(line1)AttributeError:'str'オブジェクトに属性'write'がありません

およびスクリプト自体:

f = raw_input("type filename: ")
def print_text(f):
    print f.read()
current_file = open(f)
print_text(current_file)
commands = raw_input("type 'e' to edit text or RETURN to close the file")

if commands == 'e':
    line1 = raw_input("line 1: ")
    f.write(line1)
else:
    print "closing file"
    current_file.close()
4

4 に答える 4

4

これを変える:

f.write(line1)

これに:

current_file.write(line1)

ファイルであるかのようにアクセスしているため、エラーが発生しましたがf、ユーザーが指定したファイル名のみです。開いたファイルはcurrent_file変数に格納されます。

さらに、ファイルを読み取りモードで開いています。open()のドキュメントをご覧ください:

open(name[, mode[, buffering]])

の最も一般的に使用される値はmode read 、write (ファイルが既に存在する場合はファイルを切り捨てる)、およびappending (一部の Unix システムでは、現在のシーク位置に関係なく、すべての書き込みがファイルの末尾に追加されることを意味します) です。 . モードを省略した場合、デフォルトは になります。'r''w''a''r'

于 2012-05-09T14:52:04.797 に答える
1

あなたがしているはずです:

current_file.write(line1)

どうしたの?にファイル名を保存しf、それを使用してファイル オブジェクトを開きました。ファイル オブジェクトは に保存しましたcurrent_file

エラー メッセージは、次のことを正確に伝えようとしていました:fは文字列です。文字列にはメソッドがありませんwrite。10 行write目で、変数 に格納されているオブジェクトのメソッドを呼び出そうとしましたf。うまくいきません。

プログラミングを学ぶには、エラーメッセージを読むことを学ぶ必要があります。心配しないで。進むにつれて楽になります。

于 2012-05-09T14:52:03.313 に答える
1

これを変える:

current_file = open(f)

これに:

current_file = open(f, 'w')

この:

f.write(line1)

に:

current_file.write(line1)
于 2012-05-09T14:52:12.830 に答える
0

おそらくファイルに書き込む必要がありますが、どれが文字列(結果を含む)であるかを調べていwriteますfraw_input()また、ステートメントを使用してファイルを開くことは、よりPythonicであり、より良い方法であると考えられているため、考えられるwithあらゆる場合にファイルが閉じられることが確実になります(予期しないエラーが含まれます!):

パイソン 3.x:

def print_from_file(fname):
    with open(fname, 'r') as f:
        print(f.read())

f = input("type filename: ")
with open(f, 'w') as current_file:
    print_from_file(f)
    commands = input("type 'e' to edit text or RETURN to close the file")
    if commands == 'e':
        line1 = input("line 1: ")
        current_file.write(line1)
    else:
        print("closing file")

パイソン 2.x:

def print_from_file(fname):
    with open(fname, 'r') as f:
        print f.read()

f = raw_input("type filename: ")
with open(f, 'w') as current_file:
    print_from_file(f)
    commands = raw_input("type 'e' to edit text or RETURN to close the file")
    if commands == 'e':
        line1 = raw_input("line 1: ")
        current_file.write(line1)
    else:
        print "closing file"
于 2012-05-09T14:58:11.410 に答える