在python中,当我尝试在程序中稍后访问fp时,我看到fp.readlines()正在关闭文件的证据。你可以确认这种行为,如果我还想再读一遍,我是否需要稍后再次重新打开文件?
Is the file closed?类似,但没有回答我的所有问题。
import sys
def lines(fp):
print str(len(fp.readlines()))
def main():
sent_file = open(sys.argv[1], "r")
lines(sent_file)
for line in sent_file:
print line
返回:
20
答案 0 :(得分:10)
读完文件后,文件指针已移至末尾,超过该点就不会再找到任何行。
重新打开文件或寻找回头:
sent_file.seek(0)
您的文件未已关闭;当您尝试访问它时,关闭的文件会引发异常:
>>> fileobj = open('names.txt')
>>> fileobj.close()
>>> fileobj.read()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file
答案 1 :(得分:3)
它不会关闭文件,但它会读取其中的行,因此如果不重新打开文件或将文件指针设置回fp.seek(0)
的开头,则无法再次读取它们。
作为不关闭文件的证据,请尝试更改函数以实际关闭文件:
def lines(fp):
print str(len(fp.readlines()))
fp.close()
您将收到错误:
Traceback (most recent call last):
File "test5.py", line 16, in <module>
main()
File "test5.py", line 12, in main
for line in sent_file:
ValueError: I/O operation on closed file
答案 2 :(得分:1)
它不会被关闭,但文件将在最后。如果您想再次阅读其内容,请考虑使用
f.seek(0)
答案 3 :(得分:0)
您可能想要使用with语句和上下文管理器:
>>> with open('data.txt', 'w+') as my_file: # This will allways ensure
... my_file.write('TEST\n') # that the file is closed.
... my_file.seek(0)
... my_file.read()
...
'TEST'
如果您使用普通电话,请记得手动关闭它(理论上python会关闭文件对象并根据需要进行垃圾收集):
>>> my_file = open('data.txt', 'w+')
>>> my_file.write('TEST\n') # 'del my_file' should close it and garbage collect it
>>> my_file.seek(0)
>>> my_file.read()
'TEST'
>>> my_file.close() # Makes shure to flush buffers to disk