Python:基于字符串数组创建文件

2024-04-29 14:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个程序,将去一个网站,下载所有的歌曲,他们已经发布。现在我很难为我下载的每首歌创建新的文件名。我最初得到所有的文件名和歌曲的位置(html)。但是,当我尝试为要放入的歌曲创建新文件时,出现了一个错误:

IOError: [Errno 22] invalid mode ('w') or filename

我尝试过使用不同的模式,比如“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()

Tags: thenameinforrangefind歌曲reader
1条回答
网友
1楼 · 发布于 2024-04-29 14:32:46

您需要使用filename = '%s' % (SongNames[0],)来构造名称,但是您还需要确保您的文件名是有效的-我不知道*.*的任何歌曲,但是我不想冒险这样做:

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

相关问题 更多 >