Hsun-Yi Hsieh Hsun-Yi Hsieh - 1 year ago 74
Python Question

Assigning column names in a txt file in python

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

Answer Source

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.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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download