我正在学习如何解析CSV文件并使用ElementTree和minidom将数据格式化为XML文件(用于漂亮的打印)。我已经离得那么近了,但是碰了一下我似乎无法绕过的小障碍。我有以下代码:
for csvFile in directory:
root = Element('Order')
with open(csvFile, 'rt') as f:
reader = csv.reader(f)
for row in reader:
queue = row[0]
token = row[1]
current_order = SubElement(root, 'Token', {'text':token})
details = SubElement(current_order, 'Queue',
{'queue':queue})
print prettify(root)
产生以下XML:
<?xml version="1.0" ?>
<Order>
<Token text="token">
<Queue queue="site_code"/>
</Token>
<Token text="H54FC9">
<Queue queue="Duplex_N-up"/>
</Token>
</Order>
如何从CSV输入中删除标题,以便XML看起来像这样:
<?xml version="1.0" ?>
<Order>
<Token text="H54FC9">
<Queue queue="Duplex_N-up"/>
</Token>
</Order>
谢谢!
答案 0 :(得分:3)
您是否要从csv文件中丢弃第一行?如果是这样,你可以很容易地做到这一点:
for csvFile in directory:
root = Element('Order')
with open(csvFile, 'rt') as f:
junk = next(f) #read the first line, don't do anything with it.
reader = csv.reader(f)
for row in reader:
queue = row[0]
token = row[1]
current_order = SubElement(root, 'Token', {'text':token})
details = SubElement(current_order, 'Queue',
{'queue':queue})
print prettify(root)
答案 1 :(得分:1)
如果您的CSV文件始终有标题,请在reader.next()
之后立即致电reader=csv.reader(f)