Search code examples
pythonsubdirectoryfile-rename

How to rename subfolders by copying the name of the file in the subfolder?


I'm trying to rename subfolders based on an a file name in the folder. I would like the folder name and file name to be the same. Currently I have a script that loops through all the subfolders and renames the files to the correct name. Now i need to take that "correct name" and rename the subfolder that file is in with the same name.

The current set up of the directory:

Folder A(Parent folder)

    Folder sample1(Sub folder)
       1. sample.pdf
       2. correct_name1.xml

    Folder B2(Sub folder)
       1. sample.pdf
       2. correct_name2.xml

    Folder B3(Sub folder)
       1. sample.pdf
       2. correct_name3.xml

Expected output:

 correct_name1 B1(Sub folder)
       1. correct_name1.pdf
       2. correct_name1.xml

    correct_name2 B2(Sub folder)
       1. correct_name2.pdf
       2. correct_name2.xml

    correct_name3 B3(Sub folder)
       1. correct_name3.pdf
       2. correct_name3.xml

Also if someone could help with renaming the pdf file as well that would be appreciated. The pdf file would be the exact same name as the xml.

I tried adding this inside the if statement, but it didn't rename the subfolders.

for dir in dirs:
     sub_folder = os.path.join(path,curr_fld,dir)
     print(sub_folder)
     os.rename(sub_folder,new_name2)

My code:

def rename(path)
for root, dirs, files in os.walk(path):
        for file in files:
            curr_fld = os.path.basename(root)
            old_name = os.path.join(path,curr_fld,file)

            if file.endswith(".xml"): 
                file_name, file_ext = os.path.splitext(file)
                print(file_name)

                new_name = "{}-{}-{}-{}{}".format(cfr, year, title, item_id, file_ext) # this is what i had done originally to get the correct file name
                new_name2 = os.path.join(path,curr_fld,new_name) #my correct name

                try:
                    os.rename(old_name,new_name2) 
                except WindowsError:
                     print("Didn't work!")


Solution

  • You should use root as the directory to rename if the files list contains an .xml file:

    def rename(path):
        for root, _, files in os.walk(path):
            try:
                new_name, _ = next(os.path.splitext(file) for file in files if file.endswith('.xml'))
            except StopIteration:
                continue
            os.rename(root, os.path.join(os.path.dirname(root), new_name))