Skip to main content
 首页 » 编程设计

python之如何正确重命名文件夹

2025年05月04日12jillzhang

我想以编程方式编辑文件夹名称。在 Windows 上它可以完美运行 - 在 Linux 上它有点损坏 A?A¶A¼ (Äöü)。
Unix 上的语言环境工作正常 - 使用 en_US.UTF-8 当我在脚本使用的相同路径上创建目录(称为 Äöü)时,它正确显示为 Äöü。当 Python 生成目录时,其可见为 A?A¶A¼。

输入

Äöü

实际输出

A?A¶A¼

预期输出

Aeoeue

我有一组必须替换的字符。

ä : ae         
Ä : Ae 
ö : oe 
Ö : Oe 
ü : ue 
Ü : Ue 
á : a 
à : a 
Á : A 
.... 

这是我读取文件的方式:

def __getChars(file): 
    chars = {} 
    with open(file) as f: 
        content = f.readlines() 
    for c in content: 
        c = c.split(':') 
        x = c[0].strip() 
 
        try: 
            y = c[1].strip() 
        except: 
            y = '' 
        chars[x] = y 
    return chars 

我是这样替换名字的

def __replace(string): 
    try: 
        string = string.encode('utf8') 
    except: 
        pass 
    for char in chars.keys(): 
        key = char 
        value = chars[key] 
        string = string.replace(key, value) 
    return string 

这就是我如何调用 __replace()

chars = __getChars(os.path.join(os.getcwd(), 'system', 'replace')) 
 
for path in os.listdir(root): 
    src = os.path.join(root, path) 
    if os.path.isdir(src): 
        dst = os.path.join(root, __replace(repr(path).decode('unicode-escape'))) 
        if src != dst: 
            os.rename(src, dst) 

请您参考如下方法:

问题出在这个 hack 中:

repr(path).decode('unicode-escape') 

您无法确定不同系统上的字节码编码,即使在具有不同系统编码的 Windows 或不同编译的 Python 上,例如CygWin 或 PyWin。唯一确定的方法是通过使用 unicode 路径调用 listdir 来获取 unicode 文件名列表,例如os.listdir(u'.') 或 os.listdir(root.decode('utf-8')):。以 unicode 执行所有文件系统操作要好得多。

我什至写了一个类似的简单程序,它可以在 Python 2 和 Python 3 中运行,没有任何修改,它可以将树中的所有文件和目录重命名为 ASCII。您的大多数替换,仅从字母中删除重音符号,都可以通过

from unicodedata import normalize 
out_str = normalize('NFKD', in_str).encode('ascii', 'ignore').decode('ascii')