1

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
  • 4
    Your filename is relative. You need to use os.path.join(root, filename). The same holds for newfilename. Commented Sep 3, 2015 at 16:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this. That taught me quite a bit and solved my problem.
I'm glad it solved your problem. You can also click on the tick next to the answer to accept the solution. This will also get you a badge.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.