Assigning column names in a txt file in python

落花浮王杯 提交于 2020-01-06 20:16:02

问题


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()

回答1:


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.

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

There are better ways to make the string for line, but we don't need to worry about those at the moment.



来源:https://stackoverflow.com/questions/38165636/assigning-column-names-in-a-txt-file-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!