简体   繁体   中英

How can I convert CSV file into XML format using Python

在此处输入图片说明 So far I have imported the csv file and selected the fields using csv writer.... now what is the easiest way to convert this file.csv from CSV to XML using Python (absolute beginner)?

import csv
with open('file.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    with open('file.csv', 'w') as new_file:
        fieldnames = ['RECORD_ID', 'FULL_NAME', 'ADDRESS', 'CITY', 'COUNTRY']

        csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='\t')
        csv_writer.writeheader()
        for line in csv_reader:
            csv_writer.writerow(line)

You can do this

import xml.etree.ElementTree as ET
import csv

with open('file.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    root = ET.Element('Import')
    with open('file.csv', 'w') as new_file:    
        for line in csv_reader:
            ent = ET.SubElement(root, 'Entity')
            node = ET.SubElement(ent, 'ID')
            node.text = line['RECORD_ID']

            node = ET.SubElement(ent, 'NAME')
            node.text = line['FULL_NAME']

            node = ET.SubElement(ent, 'CITY')
            node.text = line['CITY']

            node = ET.SubElement(ent, 'COUNTRY')
            node.text = line['COUNTRY']

            node = ET.SubElement(ent, 'ADDRESS')
            node.text = line['ADDRESS']

with open('output_file.xml', 'w') as f:
    f.write(ET.dump(root))

The idea is to create a root, and then for every row you add a subelement that will contain your row, and then for every column create a subelement to the row and add text to it.

Try the below. it is a light-weight version of @ygrog code

import xml.etree.ElementTree as ET
import csv

mapping = {'ID':'RECORD_ID','NAME':'FULL_NAME','CITY':'CITY','COUNTRY':'COUNTRY','ADDRESS':'ADDRESS'}
with open('file.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    root = ET.Element('Import')
    with open('file.csv', 'w') as new_file:    
        for line in csv_reader:
            ent = ET.SubElement(root, 'Entity')
            for k,v in mapping.items():
              node = ET.SubElement(ent, k)
              node.text = line[v]
with open('output_file.xml', 'w') as f:
  xml_str = ET.tostring(root, encoding='unicode')
  f.write(xml_str)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM