我目前在閱讀「瞭解Python的難題」,並已到達第16章。
我似乎無法在寫入文件後打印文件的內容。它只是打印什麼。在寫入之後無法讀取文件
from sys import argv
script, filename = argv print "We are going to erase the contents of %s" % filename print "If you don\'t want that to happen press Ctrl-C"
print "If you want to continue press enter"
raw_input("?") print "Opening the file..." target = open(filename, "w")
print "Truncating the file..." target.truncate()
print "Now i am going to ask you for 3 lines"
line_1 = raw_input("Line 1: ")
line_2 = raw_input("Line 2: ")
line_3 = raw_input("Line 3: ")
final_write = line_1 + "\n" + line_2 + "\n" + line_3
print "Now I am going to write the lines to %s" % filename
target.write(final_write)
target.close
print "This is what %s look like now" %filename
txt = open(filename)
x = txt.read() # problem happens here
print x
print "Now closing file"
txt.close
'target.close'應該是'target.close()'和相反,你應該使用'with'語句。 –
...和'txt.close'應該是'txt.close()' –
並且打開寫入已經截斷。 –