在python中下载并保存到磁盘的基本http文件?

2024-04-24 16:43:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我在这个网站上浏览了问答,想知道我的问题的答案。然而,我是一个初学者,我发现很难理解一些解决方案。我需要一个非常基本的解决方案。

有人能给我解释一下“通过http下载文件”和“在Windows下保存到磁盘”的简单解决方案吗?

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

<>我想下载的文件是500 MB以下,是.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

有人能指出错误(初级水平)并解释任何更简单的方法来做到这一点吗?

谢谢!


Tags: 文件答案importhttpurlosdeflocation
3条回答

下载文件的一种简单方法是:

import urllib

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

这将从网站下载文件并命名为file.gz。这是我最喜欢的解决方案之一,来自Downloading a picture via urllib and python

本例使用urllib库,它将直接从源中检索文件。

如前所述here

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

EDIT:如果仍要使用请求,请查看this questionthis one

我用wget

简单又好的库如果你想举例的话?

import wget

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

file_name = wget.download(file_url)

wget模块支持python 2和python 3版本

相关问题 更多 >