Python loop through folders and rename files

Question:

I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.

My file system looks as follows:

Root Directory
Folder
    File1
    File2
    File3
Folder
    File1
    File2
    File3

The code I have is:

os.chdir(rootDir)

for folder in os.listdir():
    print(folder)
    os.chdir(rootDir + 'folder')
    for f in os.listdir():
        print(f)
    os.chdir(rootDir)

So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory

Asked By: Jack Bird

||

Answers:

You need os.walk. It returns a 3-tuple (dirpath, dirnames, filenames) that you can iterate.

Answered By: chapelo

Have a look at os.walk

import os
for dir, subdirs, files in os.walk("."):
    for f in files:
        f_new = f + 'bak'
        os.rename(os.path.join(root, f), os.path.join(root, f_new))
Answered By: Hans Then
def change_files(root_dir,target_files,rename_fn):
    for fname in os.listdir(root_path):
        path = os.path.join(root_path,fname)
        if fname in target_files:
           new_name = rename_fn(fname)
           os.move(path,os.path.join(root_path,new_name)

def rename_file(old_name):
    return old_name.replace("txt","log")

change_files("/home/target/dir",["File1.txt","File2.txt"],rename_file)
Answered By: Joran Beasley

I know it’s been a while, but be aware of the extension as well while using os.rename() after os.walk().

If someone wishes to keep the same extension, then following should work:

import os

path_dir = "/dir/path"

# get all file names in the directory
for dir, subdirs, files in os.walk(path_dir):
    for f in files:
        # separating the file name and extension
        file_name = f.split('.')[0]
        ext = f.split('.')[-1]
        # new file name
        new_file_name = file_name + "<extended_part_of_the_name>" + "." + ext
        os.rename(os.path.join(path_dir, f), os.path.join(path_dir, new_file_name))
Answered By: doesnotmatter
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.