python csv文件转换成xml, 构建新xml文件
Posted 筱筱的春天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python csv文件转换成xml, 构建新xml文件相关的知识,希望对你有一定的参考价值。
csv文件
code
from xml.etree.ElementTree import Element,ElementTree,tostring import json,csv def csvtoxml(fname): with open(fname,\'r\') as f: reader=csv.reader(f) header=next(reader) root=Element(\'Daaa\') print(\'root\',len(root)) for row in reader: erow=Element(\'Row\') root.append(erow) for tag,text in zip(header,row): e=Element(tag) e.text=text erow.append(e) beatau(root) return ElementTree(root) def beatau(e,level=0): if len(e)>0: e.text=\'\\n\'+\'\\t\'*(level+1) for child in e: beatau(child,level+1) child.tail=child.tail[:-1] e.tail=\'\\n\' + \'\\t\'*level et=csvtoxml(r\'C:\\Temp\\ff.csv\') et.write(r\'C:\\Temp\\fff.xml\')
out
<Daaa> <Row> <Summary>summary1</Summary> <IssueType>2</IssueType> <Status>do do</Status> <Priority>hi</Priority> <Assignee>ui1</Assignee> <Components>11</Components> </Row> <Row> <Summary>summary2</Summary> <IssueType>3</IssueType> <Status>do do2</Status> <Priority>hi2</Priority> <Assignee>ui2</Assignee> <Components>12</Components> </Row> <Row> <Summary>summary2</Summary> <IssueType>4</IssueType> <Status>do do2</Status> <Priority>hi2</Priority> <Assignee>ui2</Assignee> <Components>13</Components> </Row> <Row> <Summary>summary4</Summary> <IssueType>5</IssueType> <Status>do do4</Status> <Priority>hi</Priority> <Assignee>ui4</Assignee> <Components>14</Components> </Row> <Row> <Summary>summary5</Summary> <IssueType>6</IssueType> <Status>do do5</Status> <Priority>hi2</Priority> <Assignee>ui5</Assignee> <Components>15</Components> </Row> <Row> <Summary>summary6</Summary> <IssueType>7</IssueType> <Status>do do6</Status> <Priority>hi2</Priority> <Assignee>ui6</Assignee> <Components>16</Components> </Row> <Row> <Summary>Summary</Summary> <IssueType>8</IssueType> <Status>Status</Status> <Priority>Priority</Priority> <Assignee>Assignee</Assignee> <Components>17</Components> </Row> <Row> <Summary>summary7</Summary> <IssueType>9</IssueType> <Status>do do7</Status> <Priority>hi7</Priority> <Assignee>ui7</Assignee> <Components>18</Components> </Row> <Row> <Summary>summary8</Summary> <IssueType>10</IssueType> <Status>do do8</Status> <Priority>hi8</Priority> <Assignee>ui8</Assignee> <Components>19</Components> </Row> </Daaa>
以上是关于python csv文件转换成xml, 构建新xml文件的主要内容,如果未能解决你的问题,请参考以下文章
python [xml文件到voc的csv文件]将voc标签转换为xml格式为csv格式#python #csv #xml