我正在阅读 Zed Shaw 的 How to Learn Python the Hard Way,但我无法正确理解这一部分。我正在尝试重写 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()
Run Code Online (Sandbox Code Playgroud)