Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. Rename files in subdirectories

Could you please help me to modify below script to change the name of files also in subdirectories.

def change():
    path = e.get()
    for filename in os.walk(path):
        for ele in filename:
            if type(ele) == type([]) and len(ele)!=0:
                for every_file in ele:

                    if every_file[0:6].isdigit():
                        number = every_file[0:6]
                        name = every_file[6:]
                        x = int(number)+y
                        newname = (str(x) + name)
                        os.rename(os.path.join(path, every_file), os.path.join(path, newname))
like image 713
MaciejPL Avatar asked Feb 28 '26 23:02

MaciejPL


1 Answers

I don't know what constraints you have on file names, therefore I wrote a general script just to show you how change their names in a given folder and all subfolders.

The test folder has the following tree structure:

~/test$ tree
.
├── bye.txt
├── hello.txt
├── subtest
│   ├── hey.txt
│   ├── lol.txt
│   └── subsubtest
│       └── good.txt
└── subtest2
    └── bad.txt

3 directories, 6 files

As you can see all files have .txt extension.

The script that rename all of them is the following:

import os


def main():
    path = "/path/toyour/folder"
    count = 1

    for root, dirs, files in os.walk(path):
        for i in files:
            os.rename(os.path.join(root, i), os.path.join(root, "changed" + str(count) + ".txt"))
            count += 1


if __name__ == '__main__':
    main()

The count variable is useful only to have different names for every file; probably you can get rid of it.

After executing the script, the folder looks like this:

~/test$ tree
.
├── changed1.txt
├── changed2.txt
├── subtest
│   ├── changed4.txt
│   ├── changed5.txt
│   └── subsubtest
│       └── changed6.txt
└── subtest2
    └── changed3.txt

3 directories, 6 files

I think that the problem in your code is that you don't use the actual root of the os.walk function.

Hope this helps.

like image 162
boh717 Avatar answered Mar 02 '26 12:03

boh717



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!