Python:为什么我的代码不能打印?

时间:2012-09-07 18:27:33

标签: python

见最后四行:

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')”,我试图通过删除我的评论让它更容易,但是,我不小心删除了这个重要的。它现在打印我想要的东西。谢谢你的帮助,我不知道为什么它现在正在工作。

1 个答案:

答案 0 :(得分: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()