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

时间:2013-07-25 22:44:52

标签: python python-3.x

我有文件名“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 个答案:

答案 0 :(得分:8)

在这里,你可以使用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))

干杯!如果您觉得这个答案有用,请不要忘记向上投票! ;)