os.rename 是在重命名为具有 UTF 字符的内容时添加一个额外的字符



这是我第一次在stackoverflow上提问,所以如果我做错了什么,请告诉我。

我正在尝试使用 os 库重命名文件。我希望文件名包含我生成的字符串中的一些非 ASCII 字符。代码如下:

for subdir, dirs, files in os.walk(startDir):
for file in files:
# some code to generate the newFileName string
os.rename(os.path.join(subdir,file), s.path.join(subdir,newFileName))

下面是 newFileName 字符串的示例:"te©st©.txt">

但是,当文件保存时,它会添加一个额外的字符:"teâ©st.txt©">

从我所做的其他阅读中,听起来utf-8实际上将某些代码映射到两个字符或类似的东西,这就是Â的来源。如果我在调用 os.rename 之前打印字符串,它会按照我期望的方式打印到终端。所以我猜它一定与 os.rename 与文件系统交互的方式有关。

我正在使用Windows。

也许你可以尝试一直使用 unicode?

path = u'99 bottles of N{greek small letter beta}eer on the wall.txt'
f = open(path, 'w')
f.write('Hello, World!n')
f.close()
import glob
print(glob.glob(path)) # ['99 bottles of βeer on the wall.txt']
import os
print(os.path.getsize(path)) # 15

最新更新