fp.readlines()是否关闭文件? [英] Does fp.readlines() close a file?

查看:63
本文介绍了fp.readlines()是否关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,当我稍后尝试在程序中访问fp时,看到fp.readlines()正在关闭文件的证据.您可以确认这种现象吗,如果我也想再次读取文件,是否需要稍后重新打开文件?

In python I'm seeing evidence that fp.readlines() is closing the file when I try to access the fp later in the program. Can you confirm this behavior, do I need to re-open the file again later if I also want to read from it again?

文件是否已关闭?相似,但是没有回答我所有的问题

Is the file closed? is similar, but didn't answer all of my questions.

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

推荐答案

读取文件后,文件指针已移到末尾,超过该点将不再找到"行.

Once you have read a file, the file pointer has been moved to the end and no more lines will be 'found' beyond that point.

重新打开文件或查找起点:

Re-open the file or seek back to the start:

sent_file.seek(0)

您的文件关闭;当您尝试访问关闭的文件时会引发异常:

Your file is not closed; a closed file raises an exception when you attempt to access it:

>>> 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.readlines()是否关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆