1
votes

I am trying to replace a character in multiple files in multiple subdirectories (over 700 files in 50 or so subfolders). This files works if I remove the path and place the file in the specific folder; however, when I try and use the os.walk function to go through all subdirectories, I get the following error:

[Error 2] The system cannot find the file specified 

It points to the last line of my code. Here is the code in its entirety:

import os

path = "C:\Drawings"

for root, dirs, files in os.walk( path ): # parse through file list in the current directory 
    for filename in files: #os.listdir( path ):
        if filename.find("~"):# > 0: # if a space is found
            newfilename = filename.replace("~","_") # convert spaces to _'s
            os.rename(filename,newfilename) # rename the file
1
Your filename is relative. You need to use os.path.join(root, filename). The same holds for newfilename. - Andrea Corbellini

1 Answers

3
votes

As has been mentioned, you need to give the rename function full paths for it to work correctly:

import os

path = r"C:\Drawings"

for root, dirs, files in os.walk( path ): # parse through file list in the current directory 
    for filename in files:
        if "~" in filename:
            source_filename = os.path.join(root, filename)
            target_filename = os.path.join(root, filename.replace("~","_")) # convert spaces to _'s
            os.rename(source_filename, target_filename) # rename the file

It is also best to add an r before your path string to stop Python trying to escape what comes after the backslash.