我正在阅读Zed Shaw如何以艰难的方式学习Python,我无法理解这一部分。我正在尝试重写txt文件的内容然后打印它,我的最后一行不能工作(打印后没有显示“我要将这些写入文件。”),它似乎工作直到我添加了.read命令......
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't 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. Goodbye!"
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(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print open(filename).read()
答案 0 :(得分:4)
您需要致电target.close()
或target.flush()
,以便新编写的内容可用于.read()
。
答案 1 :(得分:1)
通过查看您从此获得此代码的网站没有正确填写zed shaw从http://learnpythonthehardway.org/book/ex16.html输入的最后两行中的输入:
print"最后,我们关闭它。"
target.close()