在python中关闭以enumerate打开的文件

时间:2018-07-07 09:44:21

标签: python python-3.x

我正在使用此代码段从名为input_files的文件名列表中打开文件。

是否需要使用finally:块显式关闭文件?

def read_file():
    try:
        for filename in input_files:
            for line_num, line in enumerate(open(filename, encoding="utf-8"),1):
                line = line.rstrip()
                if line:
                    # do something with line and line_num
    except FileNotFoundError as err:
        print("File not found")
    # finally:
        # file.close()

4 个答案:

答案 0 :(得分:2)

如果您想在出现异常的情况下继续处理其他文件,则应使用 with 来更改try / except,该文件会自动关闭:

def read_file():
    for filename in input_files:
        try:
            with open(filename, encoding="utf-8") as f:
                for line_num, line in enumerate(f, 1):
                    line = line.rstrip()
                    if line:
                        # do something with line and line_num
        except FileNotFoundError as err:
           print("File not found", filename)

答案 1 :(得分:1)

即使发生异常,您也可以使用with open() as f可靠地关闭文件:

def read_file():
    try:
        for filename in input_files:
            with open(filename, encoding="utf-8") as f:
                for line_num, line in enumerate(f, 1):
                    line = line.rstrip()
                    if line:
                        # do something with line and line_num
    except FileNotFoundError as err:
        print("File not found")

答案 2 :(得分:0)

如果您在专用的with块中打开文件然后遍历文件的内容,则不会太混乱:

for filename in input_files:
    with open(filename) as f:
        file_content = f.readlines()
    for line_num, line in enumerate(file_content, 1):
        # do whatever

此代码更具可读性,可让Python为您处理关闭文件。但是,这是以将整个文件存储在内存中为代价的。

在Nils Werner的答案中显示了一种替代方法,其中结合了打开文件和对其进行迭代的逻辑,但以缩进级别为代价。

答案 3 :(得分:0)

您可以使用closing中的contextlib。您的代码将变为:

from contextlib import closing

def read_file():
    try:
        for filename in input_files:
            with closing(open(filename, encoding="utf-8")) as f:
                for line_num, line in enumerate(f,1):
                    line = line.rstrip()
                    if line:
                        # do something with line and line_num
    except FileNotFoundError as err:
        print("File not found")