在python中基本的http文件下载并保存到磁盘? [英] Basic http file downloading and saving to disk in python?

查看:394
本文介绍了在python中基本的http文件下载并保存到磁盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我已经在本网站上浏览了问答,以解答我的问题。但是,我是初学者,我很难理解一些解决方案。我需要一个非常基本的解决方案。



有人可以解释一个简单的解决方案来通过http下载文件和将其保存到Windows中的磁盘 ?



我不知道如何使用shutil和os模块。



我想要的文件下载不到500 MB,是一个.gz存档文件。如果有人可以解释如何提取存档并利用其中的文件,那将是非常好的!



这是一个部分解决方案,我从各种答案结合起来:

 导入请求
import os
import shutil

全局转储

def download_file():
全局转储
url =http://randomsite.com/file.gz
file = requests.get(url,stream = True)
dump = file.raw

def save_file():
全局转储
location = os.path.abspath(D:\folder\file.gz)
打开(file.gz,wb)作为位置:
sh util.copyfileobj(dump,location)
del dump

有人可以指出错误(初学者级别),并解释任何更容易的方法来做到这一点?



谢谢!

解决方案

下载文件的一种干净的方法是:

  import urllib 

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

这将从网站下载一个文件并将其命名为 file.gz 。这是我最喜欢的解决方案之一,从通过urllib和python下载图片



此示例使用 urllib 库,它将直接从源文件中获取文件。 / p>

I'm new to Python and I've been going through the Q&A on this site, for an answer to my question. However, I'm a beginner and I find it difficult to understand some of the solutions. I need a very basic solution.

Could someone please explain a simple solution to 'Downloading a file through http' and 'Saving it to disk, in Windows', to me?

I'm not sure how to use shutil and os modules, either.

The file I want to download is under 500 MB and is an .gz archive file.If someone can explain how to extract the archive and utilise the files in it also, that would be great!

Here's a partial solution, that I wrote from various answers combined:

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

Could someone point out errors (beginner level) and explain any easier methods to do this?

Thanks!

解决方案

A clean way to download a file is:

import urllib

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

This downloads a file from a website and names it file.gz. This is one of my favorite solutions, from Downloading a picture via urllib and python.

This example uses the urllib library, and it will directly retrieve the file form a source.

这篇关于在python中基本的http文件下载并保存到磁盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆