我在Python2.7中遇到unicode問題。問題是我從數據庫中獲取一些數據並將其存儲在名爲country的變量中,值爲u「Espa \ xf1a」。帶有奇怪字符的Python unicode文件名
如果我去的外殼和寫:
>>>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)
我不知道爲什麼會這樣。任何人都可以幫我嗎?提前致謝!
你不能做到這一點.....基本上使用os.system函數接受一個字符串作爲輸入,不包含任何非ASCII字符 –