Girl007
Girl007

Reputation: 175

how can I save my python output from XML file to txt

I have selected a few specific fields from my xml file. How can I sav my python OUTPUT in a txt or csv file?

so when I print the following name fields from my xml file

        # print(name1, name2, name3)

example OUTPUT:

Em, Dee, G
Joe, Lia, Sia
Bigs, Sia, Chi

        # import csv
        # with open("file.csv", "w", newline='') as csvfile:
        #     fieldnames =["name1", "name2", "name3"]
        #     thewriter =csv.dictwriter(csvfile, fieldnames=fieldnames)
        #     thewriter.writeheader()

I have tried the following however, my txt file looks really messed up

Upvotes: 0

Views: 75

Answers (1)

Prasad Deshmukh
Prasad Deshmukh

Reputation: 330

To save in CSV file:

import csv
with open('file.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    fieldnames = ['name1', 'name2', 'name3']
    writer.writerows([fieldnames])

To save in a text file:

with open('file.txt', 'w') as text_file:
    fieldnames = ['name1', 'name2', 'name3']
    text_file.writelines(", ".join(name for name in fieldnames))

Hope this willl help you.

Upvotes: 1

Related Questions