关闭文件错误的I / O操作(Python2)

时间:2017-07-22 10:34:27

标签: python python-2.7 csv stdout

我需要你作为新手的帮助。在尝试重命名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操作"错误。据我所知,用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

列表的最终结果是左侧空格(前面有空格)和列名

enter image description here

1 个答案:

答案 0 :(得分:2)

更改sys.stdout以使用print进行重定向是错误的方式,因为您将造成不可逆转的损害。

问题发生的原因是您将其重新分配给上下文管理器中的文件指针。退出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')