我是从eclipse运行的,我正在使用的文件名是ex16_text.txt(是的我输入正确.它正确地写入文件(输入出现),但是"print txt.read()"似乎没有做任何事情(打印一个空行),看到代码后的输出:
filename = raw_input("What's the file name we'll be working with?")
print "we're going to erase %s" % filename
print "opening the file"
target = open(filename, 'w')
print "erasing the file"
target.truncate()
print "give me 3 lines to replace file contents:"
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "writing lines to file"
target.write(line1+"\n")
target.write(line2+"\n")
target.write(line3)
#file read
txt = open(filename)
print "here are the contents of the %s file:" % filename
print txt.read()
target.close()
Run Code Online (Sandbox Code Playgroud)
输出:
我们将使用的文件名是什么?ex16_text.txt我们要擦除ex16_text.txt打开文件擦除文件给我3行替换文件内容:第1行:第3行:第2行:第3行:在这里写行文件是ex16_text.txt文件的内容:
您应该在写入文件后刷新文件以确保已写入字节.另请阅读警告:
注意:flush()不一定将文件的数据写入磁盘.使用flush()后跟os.fsync()来确保此行为.
如果您已完成写入并希望以只读访问权限再次打开该文件,则还应关闭该文件.请注意,关闭文件也会刷新 - 如果关闭它,则不需要先刷新.
在Python 2.6或更高版本中,您可以使用with语句自动关闭文件:
with open(filename, 'w') as target:
target.write('foo')
# etc...
# The file is closed when the control flow leaves the "with" block
with open(filename, 'r') as txt:
print txt.read()
Run Code Online (Sandbox Code Playgroud)