我在 Python2.7 中遇到 unicode 问题。事情是我从数据库中获取一些数据并将其存储在一个名为 country 的变量中,其值为 u"Espa\xf1a"。
如果我转到 shell 并编写以下内容:
>>>country
>>>u"Espa\xf1a"
>>>print country
>>>España
没关系。没问题。当我尝试创建一个名为 España.txt 的文件时出现问题,如下所示:
>>> country = u"Espa\xf1a"
>>> file = "%s.txt" % country
>>> file
u'Espa\xf1a.txt'
>>> print file
España.txt
>>> os.system("touch %s" % file)
Traceback (most recent call last):
File "<console>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 10: ordinal not in range(128)
我不知道为什么会这样。谁能帮帮我?提前致谢!
请您参考如下方法:
很可能是您的操作系统不允许您创建该文件。不要使用 touch 创建文件,而是尝试使用 python 方式。
f = open(file, 'w')
...
f.close()
我假设您正在尝试写入文件,并且希望将文件命名为“España.txt”。
