在 python 的 txt 文件中分配列名

Assigning column names in a txt file in python

我有以下代码可以从 xml 文件中提取所需的数据。我可以将它保存到终端,然后毫无问题地打开它。但是,我在将列名插入 txt 文件时遇到了麻烦。我一直在寻找答案,但没有找到正确的解决方案。有人会在这里帮助我吗?谢谢!!

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
orig_stdout = sys.stdout
sys.stdout = f

for program in root.findall('program'):

    programID = program.find('programID')
    season = program.find('season')
    print programID, season


sys.stdout = orig_stdout
f.close()

在Python中将数据写入文件的方法是在文件对象上调用.write(content),而不是将标准输出重定向到它。

不要让你的所有台词都乱用 sys.stdout,试试这个:

f = open("file.txt", "w")  # Open the file in (w)rite mode

f.write("programID,Season\n")  # Header line 
for program in root.findall("program"):
    programID = program.find("programID").text
    season = program.find("season").text
    line = programID + "," + season + "\n"
    f.write(line)

f.close()  # Outside the loop

有更好的方法来为 line 制作字符串,但我们目前不需要担心这些。