您现在的位置是:主页 > news > 外贸b2c网站建设平台/精准拓客软件哪个好

外贸b2c网站建设平台/精准拓客软件哪个好

admin2025/6/5 3:45:30news

简介外贸b2c网站建设平台,精准拓客软件哪个好,wordpress手机双模板下载地址,昆明网站推广我有一个递归目录.子目录和文件名均包含非法字符.我有一个清理名称的功能,例如它用名称中的下划线替换了空格.必须有一种更简单的方法,但我找不到重命名文件夹和文件的方法.因此,我想先重命名文件夹.for path, subdirs, files in os.walk(root):for name in subdirs:new_namecl…

外贸b2c网站建设平台,精准拓客软件哪个好,wordpress手机双模板下载地址,昆明网站推广我有一个递归目录.子目录和文件名均包含非法字符.我有一个清理名称的功能,例如它用名称中的下划线替换了空格.必须有一种更简单的方法,但我找不到重命名文件夹和文件的方法.因此,我想先重命名文件夹.for path, subdirs, files in os.walk(root):for name in subdirs:new_namecl…

我有一个递归目录.子目录和文件名均包含非法字符.我有一个清理名称的功能,例如它用名称中的下划线替换了空格.必须有一种更简单的方法,但我找不到重命名文件夹和文件的方法.因此,我想先重命名文件夹.

for path, subdirs, files in os.walk(root):

for name in subdirs:

new_name=clean_names(name)

name=os.path.join(path,name)

new_name=os.path.join(path,new_name)

os.chdir(path)

os.rename(name,new_name)

当我检查我的真实文件夹及其内容时,我看到只有第一个子文件夹名称被更正.我可以看到原因,因为os.chdir(path)更改了cwd,然后在for循环开始到第二条路径之前它没有更改.我以为在os.rename之后我可以更改cwd,但是我敢肯定有更优雅的方法可以做到这一点.如果我删除os.chdir行,则会出现filenotfound错误.

我看到以前曾有人问过重命名子目录,但是它们在命令行中.

解决方法:

您应该改用os.walk(root,topdown = False);否则,一旦顶层文件夹被重命名,os.walk将无法访问子文件夹,因为它无法再找到其父文件夹.

If optional argument topdown is True or not specified, the triple for

a directory is generated before the triples for any of its

subdirectories (directories are generated top-down). If topdown is

False, the triple for a directory is generated after the triples for

all of its subdirectories (directories are generated bottom-up). No

matter the value of topdown, the list of subdirectories is retrieved

before the tuples for the directory and its subdirectories are

generated.

请注意,您根本不需要调用os.chdir,因为传递给os.rename的所有路径都是绝对路径.

标签:python-3-x,python