我正在尝试编写一个程序来访问网站并下载他们发布的所有歌曲。现在我无法为我下载的每首歌创建新的文件名。我最初获得所有文件名和歌曲的位置(html)。但是,当我尝试为要放入的歌曲创建新文件时,我收到错误消息:
IOError:[Errno 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 :(得分:0)
您需要使用filename = '%s' % (SongNames[0],)
来构建名称但您还需要确定您的文件名是有效的 - 我不知道知道任何名为*.*
的歌曲,但我不想冒这样的话:
filename = ''.join([a.isalnum() and a or '_' for a in SongNames[0]])