아미(아름다운미소)

python file download(urllib, urllib2, tqdm) 본문

랭귀지/PYTHON

python file download(urllib, urllib2, tqdm)

유키공 2018. 1. 26. 13:00

파이썬에서 파일을 다운로드하는 방법

- Python 2에서 파일을 다운로드하는 방법
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
(Python 3+에서는 'import urllib.request'와 urllib.request.urlretrieve를 사용하십시오) 

- 파이썬에서 파일을로드하는 방법(진행 표시 줄)

import urllib2

url = "http://download.thinkbroadband.com/10MB.zip"

file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0
block_sz = 8192
while True:
    buffer = u.read(block_sz)
    if not buffer:
        break

    file_size_dl += len(buffer)
    f.write(buffer)
    status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
    status = status + chr(8)*(len(status)+1)
    print status,

f.close()
- 파이썬에서 파일을로드하는 방법(진행 표시 줄)
- https://pypi.python.org/pypi/tqdm
from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)






Comments