【问题标题】:How to fix I/O operation on closed file?如何修复关闭文件的 I/O 操作?
【发布时间】:2020-08-05 10:12:22
【问题描述】:

我有以下代码:

with open("Berry2019_Table1.txt", "r") as datafile:
    print (datafile.read().split()[11::4])

mass = datafile.read().split()[11::4]

它给了我 I/O 操作错误。我正在尝试将值列表放入变量中,那么我应该如何解决这个问题?提前致谢。

【问题讨论】:

  • 你应该缩进你的最后一行。如果您使用with 打开文件,则无法访问with 块之外的文件

标签: python io


【解决方案1】:

您正在尝试在loop 之外调用文件,因为您正在使用with,您应该使用loop 执行所有操作。所以,改为使用:

with open("Berry2019_Table1.txt", "r") as datafile:
    print (datafile.read().split()[11::4])

    mass = datafile.read().split()[11::4]

【讨论】:

    【解决方案2】:

    缩进。 当您尝试从 withas 语句中调用 datafile 时,您的“mass = datafile.read...”应该在“with open(...”中。

    【讨论】:

      【解决方案3】:

      如下操作:

      with open("Berry2019_Table1.txt", "r") as datafile:
          print (datafile.read().split()[11::4])
          mass = datafile.read().split()[11::4]
      

      with 块之外的datafile 将被关闭,因此您将无法访问它...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-27
        • 2016-03-06
        相关资源
        最近更新 更多