python - 必须在阅读前关闭文件吗? Python

标签 python

这个程序简单地获取一个文件,将其删除,允许用户输入两行放入空白文件,然后打印该文件。

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

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

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/

相关文章:

python - 如何在 zeep 中使用 wsdl 的每种方法发送 header ?

python - Django 时区 : feeling a bit confused

python - 如何在 matplotlib 中的图例上绘制一个矩形?

python - 为什么会显示这个 QLabel?

python - SQL 计数优化

python - 如何在 Python 中使用 textcat?

python - 使用 fuzzywuzzy 在 python 中的单个大型 df 中查找相似名称

python - 如何通过自定义属性将散点图与 Bokeh python 库链接?

Python 将不同文件中的行合并到一个数据文件中

python - 如何在不阻塞系统的情况下提供延迟的 AMP 回复?