使用os.walk()重命名文件夹和文件名

时间:2019-01-29 20:13:16

标签: python

我有一个文件夹,该文件夹本身包含多个文件夹和文件,文件夹名称或文件名中带有字符“〜”。 我需要替换或删除文件夹名称和文件名中的字符“〜”。

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()失败并且找不到路径。

0 个答案:

没有答案