簡體   English   中英

如何使用Python下載文件?

[英]How to Download Files using Python?

嗨,大家好。 我是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那樣的進度條。

非常感謝!

有一種更簡單的方法:

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

對於非常大的文件,您的代碼將使用大量內存,因為您將整個文件一次加載到內存中。 以塊的形式讀取和寫入數據可能更好:

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)

為什么不直接調用wget呢?

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

您的當前代碼將在寫入磁盤之前將整個流讀入內存。 因此,對於文件大於可用內存的情況,您將遇到問題。

要解決此問題,您可以一次讀取塊並將它們寫入文件。


(從帶有urllib2的Stream大二進制文件復制到文件

req = urllib2.urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as fp:
  while True:
    chunk = req.read(CHUNK)
    if not chunk: break
    fp.write(chunk)

“根據您的要求,嘗試使用各種CHUNK尺寸來找到”最佳位置“。”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM