3

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

4 回答 4

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
于 2013-05-12T14:17:32.743 回答
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
于 2013-05-12T14:18:00.137 回答
1

它不会被关闭,但文件会在最后。如果您想再次阅读其内容,请考虑使用

f.seek(0)
于 2013-05-12T14:20:19.810 回答
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
于 2013-05-12T15:14:33.297 回答