在阅读之前必须关闭文件吗?蟒蛇

时间:2016-01-07 04:12:26

标签: python

该程序只需一个文件,删除它,允许用户输入两行放入空白文件,然后打印文件。

但为什么我必须关闭文件对象并在显示新添加的行之前重新打开它?

(请注意,此版本的代码中没有打印文件。但如果您删除#' s它将正确执行)

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()

1 个答案:

答案 0 :(得分:5)

默认情况下缓冲文件对象;除非你写入足够的数据来填充缓冲区,否则它不会写入文件,直到文件被刷新或关闭(隐式刷新)。这样做是为了避免对小写进行大量(昂贵的)系统调用。您始终可以通过调用fileobj.flush()直接强制刷新。

其他一些注意事项:如果目标是打开读/写并截断文件,只需使用模式'w+'打开,而不是'r+'后跟truncate()。其次,使用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
相关问题