2012-04-16 22 views
0

私はファイルを書き留めているときにファイルを書き留めています。 pylastで与えられたテンプレートに続いて、私は必要なものを抽出するために正規表現を追加しましたが(これはOKです)、ファイルに印刷しようとするとエラーが発生し、修正方法はわかりませんPythonとそのライブラリの一部を教えています)。 私はどこかで行う必要があるエンコーディング仕様があると思われます(画面への出力の一部に非標準文字も表示されます)。私は自分の問題を解決する方法を知らない。 誰でも助けることができますか? 。 おかげファイル拡張子を使用した後にtxtファイルを書き込むエラー

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' 

ありがとうございましたどんな助けでも大変です!乾杯。

答えて

1

Python docsは言う:

バックスラッシュ()文字が がそうでなければ、このような改行、バックスラッシュ自体、 または引用符文字として特別な意味を持つ文字をエスケープするために使用されます。 \aが0x07の値を持つ単一の文字であるので、

...あなたは、文字列リテラルは

C: \a rtist.txt 

として解釈されている

top_artists_file = open("C:\artist.txt", "w") 

を言います...。

...その行ではなく、次のようになります。

# 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") 
+1

あなたはまた、生の文字列を使用することができます。 '' top_artists_file =オープン(R "C:\ artist.txt"、 "w") ''と入力します。 –

+0

は、コメントを投稿したときにそれを追加するように編集していました。 :) – bgporter

関連する問題