如何将非ASCII字符编码的文件重命名为ASCII字符编码

7
我有一个文件名叫做"abc枚.xlsx",其中包含一些非ASCII字符编码,我想把所有非ASCII字符都删除,以便将其重命名为"abc.xlsx"。
这是我尝试过的方法:
import os
import string
os.chdir(src_dir)  #src_dir is a path to my directory that contains the odd file
for file_name in os.listdir(): 
    new_file_name = ''.join(c for c in file_name if c in string.printable)
    os.rename(file_name, new_file_name)

以下错误发生在os.rename()函数处:
builtins.WindowsError: (2, 'The system cannot find the file specified')

这是在Windows系统上,sys.getfilesystemencoding() 给出的是 mbcs,如果有帮助的话。
我该怎么做来避免这个错误,并允许我更改文件名呢?

1
这是 Python 3.X,对吗?(os.listdir() 在 2.X 上会抛出异常,除非你传递一个路径) - Brigand
尝试将原始文件名转换为Unicode。您的循环将把多字节字符分解成单个字节,并且其中一些即使可打印也可能是无效的文件名字符,从而导致循环中断。 - Mark Ransom
@MarkRansom:file_name 应该已经是 Unicode 字符串(可选路径等于 '.'(Unicode 字符串),因此 listdir() 必须返回 Unicode 字符串)。 - jfs
显示导致错误的 print(ascii(file_name), ascii(new_file_name)) - jfs
@MarkRansom:listdir()在Python 3.2+中路径是可选的。 - jfs
显示剩余2条评论
1个回答

12

这里给你,它也适用于Python 2.7。

import os
import string

for file_name in os.listdir(src_dir): 
    new_file_name = ''.join(c for c in file_name if c in string.printable)
    os.rename(os.path.join(src_dir,file_name), os.path.join(src_dir, new_file_name))

加油!如果您觉得这个答案有用,请不要忘记点赞!;)


谢谢,我还不能用适当的UTF-8和正则表达式来完成这个任务,但至少它能够工作。 - Omiod

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接