连接Unicode和UTF-8 Python 2.7

3
>>> dir = u'\\\\nas\\cut\\'
>>> cutter = "seleção"
>>> ext = ".cf2"
>>> path = dir+cutter+ext

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    path = dir+cutter+ext
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 4: ordinal not in range(128)

这是需要使用的:

f = open(dir, 'r')

我不知道如何正确地连接这个。变量dir必须是Unicode编码,因为我使用configparser来解析.ini文件中的值,并且该值采用Unicode编码。

2个回答

4

将字节解码为unicode字符串:

path = dir + cutter.decode('utf8') + ext.decode('utf8')

请注意,您应该真正使用os.path.join()函数来构建路径:
path = os.path.join(dir, cutter.decode('utf8') + ext.decode('utf8'))

假设您知道终端或控制台已配置为UTF-8;在此处最好使用sys.stdin.encoding。对于从其他地方获取的数据,请首先确定该来源的编解码器。


如果他的终端不是UTF-8呢? :) - Mark Tolonen
@MarkTolonen 很好的观点;我在那里基于标签做了一个假设。在这里使用 sys.stdin.encoding 将是更好的选择。 - Martijn Pieters

0

如果您的文件名和扩展名像示例一样是常量,请为所有内容使用Unicode字符串:

>>> dir = u'\\\\nas\\cut\\'
>>> cutter = u"seleção"
>>> ext = u".cf2"
>>> path = dir+cutter+ext

如果不是常量而是字节字符串,则使用适当的编码对其进行.decode()。该编码将取决于操作系统。
请注意,一些API(如os.listdir()glob.glob())可以接受Unicode参数并返回Unicode字符串。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接