如何将 python 输出从 XML 文件保存到 txt
how can I save my python output from XML file to txt
我从 xml 文件中选择了几个特定字段。如何将我的 python 输出保存到 txt 或 csv 文件中?
所以当我从 xml 文件中打印以下名称字段时
# print(name1, name2, name3)
示例输出:
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()
我尝试了以下方法,但是我的 txt 文件看起来真的很乱
要保存为 CSV 文件:
import csv
with open('file.csv', 'w', newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
fieldnames = ['name1', 'name2', 'name3']
writer.writerows([fieldnames])
要保存在文本文件中:
with open('file.txt', 'w') as text_file:
fieldnames = ['name1', 'name2', 'name3']
text_file.writelines(", ".join(name for name in fieldnames))
希望对您有所帮助。
我从 xml 文件中选择了几个特定字段。如何将我的 python 输出保存到 txt 或 csv 文件中?
所以当我从 xml 文件中打印以下名称字段时
# print(name1, name2, name3)
示例输出:
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()
我尝试了以下方法,但是我的 txt 文件看起来真的很乱
要保存为 CSV 文件:
import csv
with open('file.csv', 'w', newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
fieldnames = ['name1', 'name2', 'name3']
writer.writerows([fieldnames])
要保存在文本文件中:
with open('file.txt', 'w') as text_file:
fieldnames = ['name1', 'name2', 'name3']
text_file.writelines(", ".join(name for name in fieldnames))
希望对您有所帮助。