在python中的txt文件中分配列名 [英] Assigning column names in a txt file in python
问题描述
我有以下代码从xml文件中提取所需的数据.我可以将其保存到终端,并可以毫无问题地打开它.但是,我在将列名插入txt文件时遇到了麻烦.我一直在寻找答案,但没有找到正确的解决方案.有人可以帮我吗?谢谢!!
I have the following code that extracts needed data from a xml file. I can save it to terminal, and open it with no problem. I am in trouble inserting column names to the txt file, however. I have been searching the answer but found no right solution. Would anyone help me here? Thank you!!
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)
,而不是将stdout重定向到该对象.
The way to write data to a file in Python is to call .write(content)
on the file object, not to redirect stdout to it.
请尝试执行以下操作,而不是将所有行弄乱sys.stdout
:
Instead of all your lines messing with sys.stdout
, try this:
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
制作字符串,但是我们现在不必担心这些问题.
There are better ways to make the string for line
, but we don't need to worry about those at the moment.
这篇关于在python中的txt文件中分配列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!