![](/img/trans.png)
[英]What is the difference between 'in fp' and 'in fp.readlines()'?
[英]Does fp.readlines() close a file?
在python中,當我嘗試在程序中稍后訪問fp時,我看到fp.readlines()正在關閉文件的證據。 你可以確認這種行為,如果我還想再讀一遍,我是否需要稍后再次重新打開文件?
文件已關閉嗎? 是類似的,但沒有回答我的所有問題。
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
讀取文件后,文件指針已移至末尾,超過該點就不會再找到任何行。
重新打開文件或尋找開頭:
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
它不會關閉文件,但它會讀取其中的行,因此如果不重新打開文件或將文件指針設置回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
它不會被關閉,但文件將在最后。 如果您想再次閱讀其內容,請考慮使用
f.seek(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.