2013-12-14 58 views
0

我正在嘗試編寫一個程序,該程序將轉到網站並下載他們發佈的所有歌曲。現在,我無法爲我下載的每首歌曲創建新的文件名。我最初獲取所有文件名和歌曲的位置(html)。然而,當我嘗試創建新的文件將被放在首歌曲,我得到一個錯誤說:Python:基於字符串數組創建文件

IO錯誤:[錯誤22]無效的模式(「W」)或文件名

我已經嘗試使用不同的模式,如「w +」,「a」和「a +」,看看這些是否能解決問題,但到目前爲止,我不斷收到錯誤消息。我也嘗試過「%name」 - 字符串,但那也沒有奏效。我的代碼如下,任何幫助將不勝感激。

import urllib 
import urllib2 

def earmilk(): 
    SongList = [] 
    SongStrings = [] 
    SongNames = [] 
    earmilk = urllib.urlopen("http://www.earmilk.com/category/pop") 
    reader = earmilk.read() 
    #gets the position of the playlist 
    PlaylistPos = reader.find("var newPlaylistTracks = ") 
    #finds the number of songs in the playlist 
    NumberSongs = reader[reader.find("var newPlaylistIds = "): PlaylistPos].count(",") + 1 
    initPos = PlaylistPos 

    #goes though the playlist and records the html address and name of the song 

    for song in range(0, NumberSongs): 
     songPos = reader[initPos:].find("http:") + initPos 
     namePos = reader[songPos:].find("name") + songPos 
     namePos += reader[namePos:].find(">") 
     nameEndPos = reader[namePos:].find("<") + namePos 
     SongStrings.append(reader[songPos: reader[songPos:].find('"') + songPos]) 
     SongNames.append(reader[namePos + 1: nameEndPos]) 
     #initPos += len(SongStrings[song]) 
     initPos = nameEndPos 

    for correction in range(0, NumberSongs): 
     SongStrings[correction] = SongStrings[correction].replace('\\/', "/") 

    #downloading songs 

    #for download in range(0, NumberSongs): 
    #print reader.find("So F*") 
    #x= SongNames[0] 
    songDL = open(SongNames[0].formant(name), "w+") 
    songDL.write(urllib.urlretrieve(SongStrings[0], SongNames[0] + ".mp3")) 
    songDL.close() 


    print SongStrings 
    for name in range(0, NumberSongs): 
     print SongNames[name] + "\n" 
    earmilk.close() 
+0

嘗試'打印SongNames [0] .formant(name)',在'open'之前, – thefourtheye

回答

0

您需要使用filename = '%s' % (SongNames[0],)構建名稱你也需要做出確保你的文件名是一個有效的 - 我不知道*.*但我的任何歌曲不想冒險,所以像這樣:

filename = ''.join([a.isalnum() and a or '_' for a in SongNames[0]])