Advertisement
Python253

csv2xml

Mar 13th, 2024
671
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: csv2xml.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts a CSV file (.csv) to an XML file (.xml).
  10. It reads the CSV content and creates an XML file with each row represented as a separate element.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'csv2xml.py'.
  17. 2. Ensure your CSV file ('example.csv') is in the same directory as the script.
  18. 3. Run the script.
  19. 4. The converted XML file ('csv2xml.xml') will be generated in the same directory.
  20.  
  21. Note: Adjust the 'csv_filename' and 'xml_filename' variables in the script as needed.
  22. """
  23. import csv
  24. import xml.etree.ElementTree as ET
  25.  
  26. def csv_to_xml(csv_filename, xml_filename):
  27.     root = ET.Element("root")
  28.     with open(csv_filename, 'r') as csvfile:
  29.         csvreader = csv.reader(csvfile)
  30.         for row in csvreader:
  31.             # Assuming each row in the CSV file is a separate element
  32.             ET.SubElement(root, "element").text = ','.join(row)
  33.  
  34.     tree = ET.ElementTree(root)
  35.     tree.write(xml_filename)
  36.  
  37. if __name__ == "__main__":
  38.     csv_filename = 'example.csv'
  39.     xml_filename = 'csv2xml.xml'
  40.     csv_to_xml(csv_filename, xml_filename)
  41.     print(f"Converted '{csv_filename}' to '{xml_filename}'.")
  42.  
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement