我在python 2中使用此函数创建文件
service-module
但是当在station_ [name]中是“Ä”或“Ü”等等时,我收到此错误
with io.FileIO(station_data['name']+".pls", "w") as file:
file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )
这是整个剧本
UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)
它基于GitHub
上的此脚本答案 0 :(得分:1)
你应该做的是将文件打开为wb
,它将以二进制模式写入文件。这样你可以将非ascii字符写入文件,为什么不使用open()命令呢?
作为提示,使用字符串格式使您的脚本看起来更整洁。
with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
file.write(txt) # don't forget to encode it if you're on Python 3
对于python 2,您不需要.encode('utf-8')
。
答案 1 :(得分:0)
尝试这样的事情:
import sys
fname = "RöckDöts!"
efname = fname.encode(sys.getfilesystemencoding())
open(efname, 'w')
看看是否有效。
答案 2 :(得分:0)
with open(u"{}.pls".format(station_data['name']), "wb") as file:
txt = u"[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name']).encode('utf-8')
file.write(txt)
它适用于此变体,它结合了您的答案