用python编写一个用德语字母如ü,ä,ß的文件

2024-04-20 09:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python2中用这个函数创建文件

 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'] )

但是,当在station中_[name]是“Ä”或“Ü”等等时,我得到了这个错误

^{pr2}$

这是整个剧本

import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'}) 
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     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)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")

它基于GitHub上的脚本


Tags: nonameioimportjsonurldataresponse
3条回答

您应该做的是以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

对于python2,不需要.encode('utf-8')。在

试试这样的方法:

import sys

fname = "RöckDöts!"
efname = fname.encode(sys.getfilesystemencoding())
open(efname, 'w')

看看能不能用。在

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)

它与你的答案组合而成的变体一起工作

相关问题 更多 >