Advertisement
Python253

txt2xml

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