Using os.walk in Python

China☆狼群 提交于 2019-12-13 02:54:07

问题


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:


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.



来源:https://stackoverflow.com/questions/32380631/using-os-walk-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!