-3

见最后四行:

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()

我试图在命令提示符上显示更新的文件,但它没有打印,打印的最后一行显示“这是更新的文件!” 更新的文件在哪里?!?!

更新:我让它工作了,我忘了包含一行“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 回答