写入文件后无法读取文件
我目前正在阅读“用困难的方式学习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
和txt.close
,而不是你只是得到他们的 指点
。由于它们是函数(或更准确地说,是方法),因此您需要()
在函数名称后调用它:file.close()
。那就是问题所在;
您以写入模式打开文件,该模式将删除文件的所有内容。您写入了文件,但从未关闭它,因此更改从未提交,文件保持为空。接下来,您以读取模式打开它,只需读取空文件。要手动提交更改,请使用
file.flush()
。或者直接关闭文件,它将自动刷新。同样,调用
target.truncate()
是无用的,因为write
如注释中所述,以模式打开时它已经自动完成。编辑
:在注释中也提到过,usingwith
语句功能非常强大,您应该改用它。您可以从http://www.python.org/dev/peps/pep-0343/中阅读更多内容,但是基本上,当与文件一起使用时,它会打开文件并在您取消缩进后自动关闭它。这样,您不必担心关闭文件,由于缩进,当您可以清楚地看到文件的使用位置时,它看起来要好得多。快速示例:
f = open("test.txt", "r") s = f.read() f.close()
可以通过使用以下
with
语句来做得更短,更好看:with open("test.txt", "r") as f: s = f.read()