首页 > 解决方案 > 如果要关闭文件,是否需要再次打开文件?

问题描述

在我的作业中,我应该在一个函数中阅读完一个文件后关闭它。但是,稍后我必须从另一个函数再次访问它。关闭文件是强制关闭文件的好习惯的要求,但我觉得没有必要,因为我需要稍后再次打开文件。有没有办法关闭文件并仍然从另一个功能访问它,或者我应该手动重新打开它。

示例代码:

def open(file):

    filename = open(file, "r")
    filename.read()
    filename.close()

def access():

    for line in filename:
        print(line)

标签: pythonpython-3.xfilefile-io

解决方案


没有什么说您必须在当前函数结束之前关闭文件,只是您必须确保文件关闭。一种方法是将已经打开的文件access作为参数传递给,并在access返回后关闭它。例如,

def access1(fh):

    for line in fh:
        print(line)

def access2(fh):
    # Do something else with the file

# This is the builtin open function, not the one in the question
with open(filename) as f:
    access1(f)
    f.seek(0)  # Reset the file pointer for the next function
    access2(f)

推荐阅读