2013-05-12 122 views
3

在python中,我看到fp.readlines()正在關閉文件,當我嘗試在程序中稍後訪問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

它不關閉文件,但它讀取所有行的它(這樣它們不能被再次除非閱讀你重新打開文件。 – 2013-05-12 14:16:02

+6

值得注意的是,當使用Python處理文件時,最好使用[with'語句](http://www.youtube.com/watch?v=lRaKmobSXF4)。 – 2013-05-12 14:20:08

+0

'print fp.closed'告訴你它是否被關閉 – georg 2013-05-12 14:47:58

回答

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 
+0

+1例外。優秀點。 – 2013-05-12 14:51:18

+0

謝謝!這非常有幫助。 – mwmath 2013-05-12 18:53:05

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 
+0

「如果不重新打開文件就不能再次讀取」不正確。 'fp.seek(0)'將文件指針重置爲開頭。 – 2013-05-12 14:39:42

1

這不會是關閉,但文件將在最後。如果你想讀的內容進行了第二次再考慮使用

f.seek(0) 
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' 

如果使用正常通話,記得要關閉它手動(理論上蟒蛇關閉文件對象和垃圾收集他們需要的話):

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