Python3 'ascii' codec不能编码字符。

时间:2023-01-06 13:21:26

I am trying to rename a file with non unicode chars in name.

我试图用非unicode字符来重命名一个文件。

import os

dir = b'/tr2'

for file_name in os.listdir(dir):
    file_name = file_name.decode('utf8','replace')
    print(file_name)
    os.rename(file_name,'11.txt')

Can only print this name, but when I try to rename, I get the error:

只能打印这个名称,但是当我试图重命名时,我得到了错误:

UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' in position 11: ordinal not in range(128)

1 个解决方案

#1


0  

The problem was in that I needed to display the value of the file_name and work with it later in the program. So thanks to Martin Evans the decision in the next:

问题在于,我需要显示file_name的值,并在程序中稍后处理它。因此,感谢马丁·埃文斯在接下来的决定:

import os

dir = b'/tr2'

for file_name in os.listdir(dir):

print(file_name.decode('utf8','replace'))

os.rename(os.path.join(dir, file_name), os.path.join(dir, b'11.txt'))

#1


0  

The problem was in that I needed to display the value of the file_name and work with it later in the program. So thanks to Martin Evans the decision in the next:

问题在于,我需要显示file_name的值,并在程序中稍后处理它。因此,感谢马丁·埃文斯在接下来的决定:

import os

dir = b'/tr2'

for file_name in os.listdir(dir):

print(file_name.decode('utf8','replace'))

os.rename(os.path.join(dir, file_name), os.path.join(dir, b'11.txt'))