首页 > 解决方案 > 使用 os.walk() 重命名文件夹和文件名

问题描述

我有一个文件夹,它本身有几个文件夹和文件,文件夹名称或文件名中带有字符“~”。我需要替换或删除文件夹名和文件名中的字符“~”。

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('x:\\')
        for filename in filenames)

# The keys of the dictionary are the values to replace, each corresponding
# item is the string to replace it with
replacements = {'~': ''}

for path in paths:
    # Copy the path name to apply changes (if any) to
    newname = path 
    # Loop over the dictionary elements, applying the replacements
    for k, v in replacements.items():
        newname = newname.replace(k, v)
    if newname != path:
        os.rename(path, newname)

我希望上面的代码可以重命名,但它说:“找不到路径”假设我有这个路径:“x:\ajaxgo~1.com\ajax\libs\jquery\110.2\jquery~1.js”pythonscript 会正确重命名所有内容并像这样生成它 "x:\ajaxgo1.com\ajax\libs\jquery\110.2\jquery1.js" 但 os.rename() 失败并且找不到路径。

标签: python

解决方案


推荐阅读