【发布时间】: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