【发布时间】:2017-12-11 03:32:06
【问题描述】:
作为我的 python 脚本的一部分,我正在测试两个文件的大小是否相同:
os.path.getsize(dir_file) # dir_file = root path + filename joined
但是当我遇到一个文件名中包含一些特殊字符(例如 Ü)时,我收到以下错误:WindowsError: [Error 2] The system cannot find the file specified 用 \xf6 之类的东西替换了特殊字符。
我尝试将dir_file 编码为 utf-8,如下所示:
unicode(dir_file, 'utf-8') # method 1
dir_file.encode('utf-8') # method 2
但这给了我以下错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 79: ordinal not in range(128)。
不知道如何解决这个字符编码问题。
【问题讨论】:
-
我们可以猜到,但您应该在标签中指定您的 Python 版本。 Python 2 和 Python 3 处理 Unicode 的方式非常不同。
-
你是如何初始化和加入变量 dir_file 的内容的?
-
@RoryDaulton 哦,好的。我正在使用 Python 2
-
@anneb
os.path.join(root, filename) -
请参阅stackoverflow.com/q/11545185,但在这些情况下也可以考虑切换到 Python 3:PEP 519helps。
标签: python string unicode ascii python-2.x