0

我在写入使用 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'

非常感谢您的帮助!干杯。

4

1 回答 1

1

Python 文档说:

反斜杠 () 字符用于转义具有特殊含义的字符,例如换行符、反斜杠本身或引号字符。

...所以当你说

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")
于 2012-04-16T23:43:04.067 回答