简体   繁体   中英

Using os.walk in Python

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM