Python 在CSV文件中,每个字母都有自己的列
对于print语句,它的显示方式正是我想要的Python 在CSV文件中,每个字母都有自己的列,python,xml,csv,Python,Xml,Csv,对于print语句,它的显示方式正是我想要的 import os, csv from xml.etree import ElementTree file_name = "example.xml" full_file = os.path.abspath(os.path.join("xml", file_name)) dom = ElementTree.parse(full_file) Fruit = dom.findall("Fruit") with open('test.csv','w')
import os, csv
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")
with open('test.csv','w') as fp:
a = csv.writer(fp, delimiter=',')
for f in Fruit:
Explanation = f.find("Explanation").text
Types = f.findall("Type")
for t in Types:
Type = t.text
print ("{0}, {1}".format(Type, Explanation))
a.writerows("{0}, {1}".format(Type, Explanation))
等等
但是,在CSV文件中,每个字母都有自己的列。我想在CSV文件的第一列输入,在第二列输入解释
Orange, They belong to the Citrus family.
Lemon, They belong to the Lemon family.
根据我(非常有限)的经验,我发现要向CSV写入,必须将单元格所需的文本放在单独的方括号中,例如:
Column1 Column2
Orange They belong to the Citrus family.
Lemon They belong to the Citrus family.
因此,它应在CSV中显示为:
a.writerow([Type]+[Explanation])
希望这有帮助:)您应该使用
writerow
,而不是writerows
。你应该给它一个列表,而不是字符串
Column 1 Column 2
Type Explanation
Column 1 Column 2
Type Explanation
a.writerow([Type, Explanation])