Advertisement
Python253

xml2csv

Mar 16th, 2024
514
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: xml2csv.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. Description:
  9. This script converts an XML file (.xml) to a CSV file (.csv).
  10. It extracts data from specific elements in the XML and writes it to the CSV file.
  11.  
  12. Requirements:
  13. - Python 3.x
  14.  
  15. Usage:
  16. 1. Save this script as 'xml2csv.py'.
  17. 2. Ensure your XML file ('example.xml') is in the same directory as the script.
  18. 3. Update the 'your_element_path' and field names in the script based on your XML structure.
  19. 4. Run the script.
  20. 5. The converted CSV file ('xml2csv.csv') will be generated in the same directory.
  21.  
  22. Note: Adjust the 'xml_file' and 'csv_file' variables in the script as needed.
  23. """
  24.  
  25. import xml.etree.ElementTree as ET
  26. import csv
  27.  
  28. def xml_to_csv(xml_file, csv_file):
  29.     tree = ET.parse(xml_file)
  30.     root = tree.getroot()
  31.  
  32.     with open(csv_file, 'w', newline='') as csvfile:
  33.         csvwriter = csv.writer(csvfile)
  34.  
  35.         # Update 'your_element_path' and field names based on your XML structure
  36.         for element in root.findall('.//your_element_path'):
  37.             # Extract data and write to CSV
  38.             csvwriter.writerow([element.find('field1').text, element.find('field2').text, ...])
  39.  
  40. if __name__ == "__main__":
  41.     # Set the filenames for the XML and CSV files
  42.     xml_file = 'example.xml'
  43.     csv_file = 'xml2csv.csv'
  44.  
  45.     # Convert the XML to a CSV file
  46.     xml_to_csv(xml_file, csv_file)
  47.  
  48.     print(f"Converted '{xml_file}' to '{csv_file}'.")
  49.  
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement