不知道大家有没有遇到这样的问题,就是url源不稳定,时不时下载到空文件,我终于想到了一个解决的好办法,分享给大家。
def downloadfile(url,filename=None):
if(not filename): #如果参数没有指定文件名
filename=os.path.basename(url) #取用url的尾巴为文件名
leng=1
while(leng==1):
torrent=requests.get(url,headers=headers)
leng=len(list(torrent.iter_content(1024))) #下载区块数
if(leng==1): #如果是1 就是空文件 重新下载
print(filename,'下载失败,重新下载')
sleep(1)
else:
print(path,'下载完成')
with open(filename,'wb') as f:
for chunk in torrent.iter_content(1024): #防止文件过大,以1024为单位一段段写入
f.write(chunk)
当遇到URL源不稳定导致偶尔下载到空文件的问题时,可以使用该方法来解决。通过检查下载区块数,如果为1则重新尝试下载,并在下载完成后以1024字节为单位写入文件,确保文件完整。

被折叠的 条评论
为什么被折叠?



