繁体   English   中英

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM