我是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代码中的文件夹中。
请帮助。
答案 0 :(得分:2)
您需要了解内容配置问题'标题,请参阅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')