这个程序简单地获取一个文件,将其删除,允许用户输入两行放入空白文件,然后打印该文件。
但为什么我必须关闭文件对象并在它显示新添加的行之前重新打开它?
(请注意,此版本的代码中未打印文件。但如果删除 #,它将正确执行)
from sys import argv
sript, filename = argv
print "We will be buliding a new file from an %s" % filename
print "If you don't want to do this, hit CTRL_C"
print "If you do, hit and other key"
raw_input(">>>")
print "Oppening the file..."
file_ob = open(filename, "r+")
file_ob.truncate()
print "Now we will rewrite this file with the following line"
line1 = raw_input("The fist line will be :")
line2 = raw_input("The second line will be:")
print "Now we're put them into the file"
file_ob.write("\n\t>>>" + line1 + "\n\n\t>>>" + line2)
print "And now we will see what is in the file we just made"
print file_ob.read()
file_ob.close()
print "And now we will see what is in the file we just made"
#file_ob = open(filename, "r+")
#print file_ob.read()
#file_ob.close()
最佳答案
文件对象默认是缓冲的;除非您写入足够的数据来填充缓冲区,否则它不会写入文件,直到文件被刷新或关闭(隐式刷新)。这样做是为了避免为小写操作进行大量(昂贵的)系统调用。您始终可以通过调用 fileobj.flush()
直接强制刷新。
一些其他注意事项:如果目标是打开文件进行读/写并截断文件,只需使用 'w+'
模式打开,而不是 'r+'
后跟截断()
。其次,使用 with
语句,这样您就不会意外地无法关闭文件(通过省略 close
,或者由于抛出异常而绕过它)。示例:
with open(filename, "w+") as file_ob:
# Don't need to truncate thanks to w+
# Do writes/reads, with explicit flushes if needed
# When block exited by any means, file is flushed and closed automatically
关于python - 必须在阅读前关闭文件吗? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647239/