Programing

파이썬에서 디스크에 기본 http 파일 다운로드 및 저장?

crosscheck 2020. 6. 20. 10:30
반응형

파이썬에서 디스크에 기본 http 파일 다운로드 및 저장?


저는 Python을 처음 사용하고 있으며이 사이트의 질문에 대한 답변을 위해 Q & A를 진행했습니다. 그러나 나는 초보자이며 일부 솔루션을 이해하기가 어렵습니다. 매우 기본적인 솔루션이 필요합니다.

누군가 'http를 통해 파일 다운로드'와 'Windows의 디스크에 파일 저장'에 대한 간단한 해결책을 설명해 주시겠습니까?

shutil 및 os 모듈을 사용하는 방법을 잘 모르겠습니다.

다운로드하려는 파일이 500MB 미만이고 .gz 아카이브 파일입니다. 누군가 아카이브를 추출하고 파일을 활용하는 방법을 설명 할 수 있다면 좋을 것입니다!

다음은 다양한 답변을 결합하여 작성한 부분 솔루션입니다.

import requests
import os
import shutil

global dump

def download_file():
    global dump
    url = "http://randomsite.com/file.gz"
    file = requests.get(url, stream=True)
    dump = file.raw

def save_file():
    global dump
    location = os.path.abspath("D:\folder\file.gz")
    with open("file.gz", 'wb') as location:
        shutil.copyfileobj(dump, location)
    del dump

누군가가 오류 (초보자 수준)를 지적하고 더 쉬운 방법을 설명 할 수 있습니까?

감사!


파일을 다운로드하는 확실한 방법은 다음과 같습니다.

import urllib

testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")

웹 사이트에서 파일을 다운로드하고 이름을 지정합니다 file.gz. 이것은 urllib 및 python을 통해 그림 다운로드 에서 내가 가장 좋아하는 솔루션 중 하나입니다 .

이 예제는 urllib라이브러리 를 사용 하며 소스에서 파일을 직접 검색합니다.


여기에 언급 한 바와 같이 :

import urllib
urllib.urlretrieve ("http://randomsite.com/file.gz", "file.gz")

EDIT:여전히 요청을 사용하려면 이 질문 또는 질문을 살펴보십시오 .


wget을 사용 합니다.

예를 들어 간단하고 좋은 도서관?

import wget

file_url = 'http://johndoe.com/download.zip'

file_name = wget.download(file_url)

wget 모듈은 python 2 및 python 3 버전을 지원합니다


wget, urllib 및 request를 사용하는 네 가지 방법.

#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile as profile
import urllib
import wget


url = 'https://tinypng.com/images/social/website.jpg'

def testRequest():
    image_name = 'test1.jpg'
    r = requests.get(url, stream=True)
    with open(image_name, 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)

def testRequest2():
    image_name = 'test2.jpg'
    r = requests.get(url)
    i = Image.open(StringIO(r.content))
    i.save(image_name)

def testUrllib():
    image_name = 'test3.jpg'
    testfile = urllib.URLopener()
    testfile.retrieve(url, image_name)

def testwget():
    image_name = 'test4.jpg'
    wget.download(url, image_name)

if __name__ == '__main__':
    profile.run('testRequest()')
    profile.run('testRequest2()')
    profile.run('testUrllib()')
    profile.run('testwget()')

testRequest-20.236 초 내에 4469882 함수 호출 (4469842 기본 호출)

testRequest2-0.072 초 안에 8580 개의 함수 호출 (8574 개의 원시 호출)

testUrllib - 3810 function calls (3775 primitive calls) in 0.036 seconds

testwget - 3489 function calls in 0.020 seconds


Exotic Windows Solution

import subprocess

subprocess.run("powershell Invoke-WebRequest {} -OutFile {}".format(your_url, filename), shell=True)

For Python3+ URLopener is deprecated. And when used you will get error as below:

url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'

So, try:

import urllib.request 
urllib.request.urlretrieve(url, filename)

I started down this path because ESXi's wget is not compiled with SSL and I wanted to download an OVA from a vendor's website directly onto the ESXi host which is on the other side of the world.

I had to disable the firewall(lazy)/enable https out by editing the rules(proper)

created the python script:

import ssl
import shutil
import tempfile
import urllib.request
context = ssl._create_unverified_context()

dlurl='https://somesite/path/whatever'
with urllib.request.urlopen(durl, context=context) as response:
    with open("file.ova", 'wb') as tmp_file:
        shutil.copyfileobj(response, tmp_file)

ESXi libraries are kind of paired down but the open source weasel installer seemed to use urllib for https... so it inspired me to go down this path


Another clean way to save the file is this:

import csv
import urllib

urllib.retrieve("your url goes here" , "output.csv")

참고URL : https://stackoverflow.com/questions/19602931/basic-http-file-downloading-and-saving-to-disk-in-python

반응형