2013-05-12 64 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 
相关问题