我在写一个文件时遇到问题,我正在使用pylast。按照pylast中给出的模板,我添加了一个正则表达式来提取我需要的东西(这样做没问题),但是当我尝试打印到文件时,我收到错误,并且不知道如何修复它(我我自学python和它的一些库)。 我怀疑我需要在某处创建一个编码规范(屏幕的一些输出也显示非标准字符)。我不知道如何解决我的问题。 有人可以帮忙吗? 感谢
import re
import pylast
RawArtistList = []
ArtistList = []
# You have to have your own unique two values for API_KEY and API_SECRET
# Obtain yours from http://www.last.fm/api/account for Last.fm
API_KEY = "XXX"
API_SECRET = "YYY"
###### In order to perform a write operation you need to authenticate yourself
username = "username"
password_hash = pylast.md5("password")
network = pylast.LastFMNetwork(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)
## _________INIT__________
COUNTRY = "Germany"
#---------------------- Get Geo Country --------------------
geo_country = network.get_country(COUNTRY)
#---------------------- Get artist --------------------
top_artists_of_country = str(geo_country.get_top_artists())
RawArtistList = re.findall(r"u'(.*?)'", top_artists_of_country)
top_artists_file = open("C:\artist.txt", "w")
for artist in RawArtistList:
print artist
top_artists_file.write(artist + "\n")
top_artists_file.close()
我尝试创建的文件“artist.txt”的名称更改为“x07rtist.txt”,错误开始显示。我明白了:
Traceback (most recent call last):
File "C:\music4A.py", line 32, in <module>
top_artists_file = open("C:\artist.txt", "w")
IOError: [Errno 22] invalid mode ('w') or filename:'C:\x07rtist.txt'
非常感谢您的帮助!欢呼声。
答案 0 :(得分:1)
反斜杠()字符用于转义字符 否则具有特殊含义,例如换行符,反斜杠本身, 或引号字符。
...所以当你说
时top_artists_file = open("C:\artist.txt", "w")
该字符串文字被解释为
C: \a rtist.txt
...其中\a
是一个值为0x07的单个字符。
......该行应改为:
# doubling the backslash prevents misinterpreting the 'a'
top_artists_file = open("C:\\artist.txt", "w")
或
# define the string literal as a raw string to prevent the escape behavior
top_artists_file = open(r"C:\artist.txt", "w")
或
# forward slashes work just fine as path separators on Windows.
top_artists_file = open("C:/artist.txt", "w")