create a loop through the xml file of a folder and change their name by another name in python

To loop through XML files in a folder and change their names in Python, you can use the os and ElementTree modules.

First, import the required modules.

main.py
import os
import xml.etree.ElementTree as ET
45 chars
3 lines

Specify the directory path where your XML files are stored.

main.py
xml_dir_path = "/path/to/xml/files"
36 chars
2 lines

Use the os.listdir() function to loop through all the files in the directory. For each file, open it using the ET.parse() function and get the root element using the getroot() method.

Then, rename the file using the os.rename() function with the new file name.

Here's an example code snippet that renames all the XML files in a folder from .xml to .txt.

main.py
for filename in os.listdir(xml_dir_path):
    if filename.endswith(".xml"):
        xml_path = os.path.join(xml_dir_path, filename)
        tree = ET.parse(xml_path)
        root = tree.getroot()

        # Rename the file
        os.rename(xml_path, xml_path[:-4] + ".txt")
275 chars
9 lines

This code snippet checks if the file extension is .xml, opens the file using ET.parse(), and gets the root element using getroot(). It then renames the file using the os.rename() function.

You can modify this code to change the file name to any other name you want.

gistlibby LogSnag