Skip to content Skip to sidebar Skip to footer

Python Script Recursively Rename All Files In Folder And Subfolders

Hi I have a number of different files that need to be renamed to something else. I got this far but I want to have it so that I can have many items to replace and their correspond

Solution 1:

Is this wath you want?

import os, glob
#searches for roots, directory and files#Path
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta"# rename arquivo1.txt to arquivo33.txt and arquivo2.txt to arquivo44.txt
renames={"arquivo1.txt":"arquivo33.txt","arquivo2.txt":"arquivo44.txt"}
for root,dirs,files in os.walk(p):
   for f in files:
      if f in renames.keys():#string you want to renametry:
            os.rename(os.path.join(root , f), os.path.join(root , renames[f]))
            print("Renaming ",f,"to",renames[f])
         except FileNotFoundError as e:
            print(str(e))

Check if this is wath you want!!!

import os, glob
#searches for roots, directory and files#Python 2.7#Path 
p=r"C:\\Users\\joao.limberger\\Documents\\Nova Pasta"#  if the substring in the key exist in filename, replace the substring #   from the value of the key#   if the key is "o1" and the value is "oPrinc1" and the filename is#  arquivo1.txt ... The filename whil be renamed to "arquivoPrinc1.txt"
renames={"o1":"oPrinc1","oldSubs":"newSubs"}
for root,dirs,files in os.walk(p):
    for f in files:
        for r in renames:
            if r in f:
                newFile = f.replace(r,renames[r],1)
                try:
                    os.rename(os.path.join(root , f), os.path.join(root , newFile))
                    print"Renaming ",f,"to",newFile
                except FileNotFoundError , e:
                    printstr(e)

Solution 2:

The first thing you'd need is a dictionary for the replacements, then a small change in your code:

import os, glob

name_map = {
     "Cat5e_1mBend1bottom50m2mBend2top": 'Cat5e50m1mBED_50m2mBE2U'
}

#searches for roots, directory and filesfor root,dirs,files in os.walk(r"H:\My Documents\CrossTalk"):
   for f in files:
       if f in name_map:
          try:
             os.rename(os.path.join(root, f), os.path.join(root, name_map[f]))
          except FileNotFoundError, e:
          #except FileNotFoundError as e:  # python 3print(str(e))

In the name_map, the key (string to the left of ":") is the name of the file in your filesystem, and the value (string to the right of the ":") is the name you want to use.

Post a Comment for "Python Script Recursively Rename All Files In Folder And Subfolders"