-3

最後の 4 行を参照してください。

from sys import argv

script, filename = argv
print "we're going to erase %r." % filename

txt = open(filename)
print txt.read()
print "If you do not want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Good bye!"
target.truncate()

print "now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."
target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.close() #Need to close the file when done editing, or else cant open.

print "Here's the updated file!"
txt = open(filename)
print txt.read()

コマンドプロンプトで更新されたファイルを表示しようとしていますが、印刷されず、印刷された最後の行に「Here's the updated file!」と表示されます。更新されたファイルはどこにありますか?!?!

更新: 動作するようになりました。「target = open(filename, 'w')」という行を含めるのを忘れていました。コメントを削除して見やすくしようとしましたが、誤ってこの重要なピースを削除してしまいました。今も私が欲しいものを印刷しています。助けてくれてありがとう、なぜ今働いているのか分かりません。

4

1 に答える 1

0

ファイルを閉じて再度開く必要はありません。

target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.close() #Need to close the file when done editing, or else cant open.

print "Here's the updated file!"
txt = open(filename)
print txt.read()

ファイルを「w+」モードで開くだけで、seek()配置でき0ます。ファイルの先頭。

target.write("%s\n%s\n%s\n" % (line1, line2, line3))
target.seek(0)

print "Here's the updated file!"    
print txt.read()

'w' または 'w+' を使用して書き込み用にファイルを開くと、ファイルの内容が削除されます。理由はありませんtruncate()

于 2012-09-07T20:41:10.373 に答える