【问题标题】:What is wrong with unclosed opened file in Python 3?Python 3 中未关闭的打开文件有什么问题?
【发布时间】:2019-10-06 08:48:33
【问题描述】:

假设我有以下代码试图从列表中打印出一些文件并使用单个循环变量循环每个文件。在外循环的每次迭代之后,我都会失去对刚刚打印出来的打开文件的引用。嗯.. 我很惊讶这段代码到底有多糟糕...如果系统定义了打开文件的最大数量,我想不出它会造成任何其他危害。 ..等等

file_names = ["a.txt","b.txt","c.txt"]
for file_name in file_names:
    file = open(file_name)
    for line in file:
        print(line)
    print("\n\n\n")

【问题讨论】:

    标签: python-3.x file operating-system filesystems


    【解决方案1】:

    您可以在此处阅读有关副作用的信息:Is explicitly closing files important?

    它可能在大多数情况下都可以工作,直到它不起作用;)

    为避免与未关闭的文件引用相关的任何问题,您应该使用with open(file_name) as file:,如下所述:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

    【讨论】:

      猜你喜欢
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多