【问题标题】:How to download file with default name and type in Python [duplicate]如何下载具有默认名称的文件并输入Python [重复]
【发布时间】:2016-12-30 09:25:07
【问题描述】:

我是Python新手,发现了一个下载数据并将数据保存为demofile.csv的代码

   import requests

    url = "https://example.com/demofile"
    r = requests.get(url)

    filename = url.split('/')[-1]

    with open(filename+".csv", "wb") as code:
        code.write(r.content)

现在,我不想明确指定任何名称。 我只希望通过 Python 脚本打开该 URL,并使用其默认名称和类型(我们手动下载文件时出现的名称和类型)下载文件。

另外,这个文件应该保存在其他目录中,而不是保存python代码的文件夹。

请在这方面提供帮助。

【问题讨论】:

标签: python web-scraping python-requests


【解决方案1】:

您需要查看“Content-Disposition”标头,请参阅 kender 的解决方案。

How to download a file using python in a 'smarter' way?

发布修改后的解决方案,可以指定输出文件夹:

from os.path import basename
import os
from urlparse import urlsplit
import urllib2

def url2name(url):
    return basename(urlsplit(url)[2])

def download(url, out_path):
    localName = url2name(url)
    req = urllib2.Request(url)
    r = urllib2.urlopen(req)
    if r.info().has_key('Content-Disposition'):
        # If the response has Content-Disposition, we take file name from it
        localName = r.info()['Content-Disposition'].split('filename=')[1]
        if localName[0] == '"' or localName[0] == "'":
            localName = localName[1:-1]
    elif r.url != url: 
        # if we were redirected, the real file name we take from the final URL
        localName = url2name(r.url)

    localName = os.path.join(out_path, localName)
    f = open(localName, 'wb')
    f.write(r.read())
    f.close()

download("https://example.com/demofile", '/home/username/tmp')

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
相关资源
最近更新 更多