如何用Python下载文件?

4 投票
4 回答
5326 浏览
提问于 2025-04-16 08:18

大家好,我是Python的新手,目前在CentOS上使用Python 2.5。

我需要像WGET那样下载文件。

我查了一些资料,发现有一些解决方案,其中一个明显的方法是:

import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
output = open('test.mp3','wb')
output.write(mp3file.read())
output.close()

这个方法运行得很好。不过我想知道,如果要下载的mp3文件非常大,比如1GB、2GB甚至更大,这段代码还能用吗?有没有更好的方法在Python中下载大文件,可能还带有像WGET那样的进度条。

非常感谢!

4 个回答

2

那为什么不直接用 wget 呢?

import os
os.system ("wget http://www.example.com/songs/mp3.mp3")
3

对于非常大的文件,你的代码会占用很多内存,因为你是一次性把整个文件都加载到内存里。这样做可能不太好,建议分块读取和写入数据:

from __future__ import with_statement
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
    while True:
        buf = mp3file.read(65536)
        if not buf:
            break
        output.write(buf)
16

有一个更简单的方法:

import urllib
urllib.urlretrieve("http://www.example.com/songs/mp3.mp3", "/home/download/mp3.mp3")

撰写回答