【发布时间】:2020-02-19 04:02:51
【问题描述】:
这是我第一次在 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。
【问题讨论】:
-
显示
print(ascii(newFileName))的输出。 -
'te\xc2\xa9st\xc2\xa9.txt'
-
如果是
str(文本),ASCII repr 应该是'te\xa9st\xa9.txt'。如果它是 UTF-8 编码的bytes,则 ASCII repr 应该是b'te\xc2\xa9st\xc2\xa9.txt'。您实际拥有的似乎是 UTF-8 解码为 Latin-1 或 Windows 代码页 1252。确保您的源文件编码为 UTF-8 并准确使用newFileName = "te©st©.txt"。
标签: python-3.x windows filenames utf iso-8859-1