-1

I have a root folder with several folders and files and I need to use Python to rename all matching correspondences. For example, I want to rename files and folders that contain the word "test" and replace with "earth"

I'm using Ubuntu Server 18.04. I already tried some codes. But I'll leave the last one I tried. I think this is really easy to do but I don't have almost any knowledge in py and this is the only solution I have currently.

import os

def replace(fpath, test, earth):
    for path, subdirs, files in os.walk(fpath):
        for name in files:
            if(test.lower() in name.lower()):
                os.rename(os.path.join(path,name), os.path.join(path,
                                            name.lower().replace(test,earth)))

Is expected to go through all files and folders and change the name from test to earth

Kulcanhez
  • 1
  • 1
  • 1

1 Answers1

2

Here's some working code for you:

def replace(fpath):
    filenames = os.listdir()
    os.chdir(fpath)
    for file in filenames:
        if '.' not in file:
            replace(file)
        os.rename(file, file.replace('test', 'earth'))

Here's an explanation of the code:

  • First we get a list of the filenames in the directory
  • After that we switch to the desired folder
  • Then we iterate through the filenames
  • The program will try to replace any instances of 'test' in each filename with 'earth'
  • Then it will rename the files with 'test' in the name to the version with 'test' replaced
  • If the file it is currently iterating over is a folder, it runs the function again with the new folder, but after that is done it will revert back to the original

Edited to add recursive iteration through subfolders.

Dan Lewis
  • 70
  • 1
  • 8