如何将具有非ASCII字符编码的文件重命名为ASCII [英] How to rename a file with non-ASCII character encoding to ASCII

查看:154
本文介绍了如何将具有非ASCII字符编码的文件重命名为ASCII的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文件名为"abc枚.xlsx",其中包含某种非ASCII字符编码,我想删除所有非ASCII字符以将其重命名为"abc.xlsx".

I have the file name, "abc枚.xlsx", containing some kind of non-ASCII character encoding and I'd like to remove all non-ASCII characters to rename it to "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.

This is on a Windows system, sys.getfilesystemencoding() gives me mbcs, if that helps any.

该如何避免该错误并允许我更改文件名?

What should I do to circumvent this error and allow me to change the file name?

推荐答案

在这里,它也适用于python 2.7

Here you go, this works with python 2.7 as well

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))

干杯!如果您认为此答案有用,别忘了投票! ;)

Cheers! Don't forget to up-vote if you find this answer useful! ;)

这篇关于如何将具有非ASCII字符编码的文件重命名为ASCII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆