为什么这个Python脚本不能在Windows上正确编写mp3文件?

时间:2014-09-27 04:45:43

标签: python url file-io

我写了这个脚本来从我的内联网音乐播放器上的播放列表中下载歌曲。脚本似乎在Ubuntu中工作正常但在Windows中它没有正确地写入mp3文件而且只有2-3秒的噪音在每个文件中,没有别的。

import urllib2
import json
import os
import argparse

parser = argparse.ArgumentParser(description="Jukebox Playlist Downloader")
parser.add_argument("playlist_Name", help="Enter the name of the shared Playlist")

download_url = "https://channeli.in/songsmedia/download/songs/english/"
playlist_url = "https://channeli.in/jukebox/playlists_public/"
user_url = "https://channeli.in/jukebox/playlists/"

#playlist_name = raw_input('Enter playlist name: ')
args = parser.parse_args()
playlist_name = args.playlist_Name


js = urllib2.urlopen(playlist_url)
js_load = json.load(js)

id = ''
#pn = "u'"+playlist_name+"'"
#print pn
for l in js_load:
    ##print l['name']
    if(l['name']==playlist_name):
        id = l['id']

if(id==''):
     print "Sorry, playlist not found"
     ##return

playlist = urllib2.urlopen(user_url+str(id))
playlist = json.load(playlist)
songs_list = playlist['songs_list']

location = "Downloads/Jukebox/"+playlist_name+"/"
if not os.path.exists(location):
    os.makedirs(location)

for song in songs_list:
    file_name = songs_list[song]['file_name']
    url_file_name = file_name.replace(' ','%20')
    song_download = urllib2.urlopen(download_url+url_file_name)
    name = file_name.split('/')[-1]
    if not os.path.exists(location+name):
        local_file = open(location+name,'w')
        local_file.write(song_download.read())
        local_file.close()
    print "Downloaded Song: "+name

1 个答案:

答案 0 :(得分:0)

您需要以二进制模式打开文件。尝试指定" b"在open()

的模式参数中
local_file = open(location+name, 'wb')

不是问题的原因,但您还应该使用os.path.join()来构建路径:

import os.path
location = os.path.join('Downloads', 'Jukebox', playlist_name)
.
.
.
local_file = open(os.path.join(location, name, 'wb')
相关问题