【问题标题】:I/O operation on closed file error (Python2)关闭文件错误的 I/O 操作(Python2)
【发布时间】:2017-07-22 10:34:26
【问题描述】:

作为新手,我需要您的帮助。我在尝试重命名 txt 文件列表中的列时遇到问题。 在重命名之前,我删除了空格

with open("smpl_list.txt", "r") as m, open ("smpl.txt","w") as n:
sys.stdout=n
for line in m:
    print line.strip()

在我导入 pandas 以重命名列之后

import pandas as pd
df=pd.read_csv("smpl.txt", sep=" ", header=None, names=["a","b","c","d"])
print (df)

但我经常收到“对已关闭文件的 I/O 操作”错误。据我所知,with block 会自动关闭文件,但问题出在哪里,我真的完全看不出来。

编辑:这是我的工作代码,贡献了@COLDSPEED

with open("smpl_list.txt", "r") as m, open ("smpl.txt","w") as n:
for line in m:
    n.write(line.strip()+"\n")

以及重命名列的第二部分

import pandas as pd
with open ("smp.txt", "w") as r:
    df=pd.read_csv("smpl.txt", sep=" ", header=None, names=["a","b","c","d"])
    print>> r, df

列表的最终结果没有剩余空间(之前有)和列名

【问题讨论】:

  • 请先修正缩进,然后再询问您的代码有什么问题。
  • 它已经在脚本中正确缩进了,但是很抱歉,当我粘贴它时,缩进消失了。

标签: python python-2.7 csv stdout


【解决方案1】:

sys.stdout 更改为使用打印进行重定向是错误的做法,因为您会造成不可逆转的损害。

问题发生是因为您将其重新分配给上下文管理器中的文件指针。退出with 块后,管理器会自动关闭,因此sys.stdout 指向一个已关闭的文件,这就是您收到该错误的原因。

您有 2 个选项。第一种选择是通过重新加载sys 来解决此问题。你可以用

import imp
imp.reload(sys)

第二个更好的选择(我更喜欢)是根本不陷入这种情况。 Python2 的 print 语句有一个语法,可以让你重定向而不必跳过箍:

with open("smpl_list.txt", "r") as m, open ("smpl.txt","w") as n:
    for line in m:
        print >> n, line.strip()

或者,稍微好一点:

with open("smpl_list.txt", "r") as m, open ("smpl.txt","w") as n:
    for line in m:
        n.write(line.strip() + '\n')

【讨论】:

  • 当然很抱歉。我应该说n.write(line) 更有效率。它是。 :) 我为混淆道歉。
  • @COLDSPEED 感谢您对 sys.stdout 和 print >> n 的好点,line.strip() 对我来说是一个很棒的解决方案。非常感谢
  • @Z.Grey 很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
相关资源
最近更新 更多