简体   繁体   中英

Download csv file through python (url)

I work on a project and I want to download a csv file from a url. I did some research on the site but none of the solutions presented worked for me.

The url offers you directly to download or open the file of the blow I do not know how to say a python to save the file (it would be nice if I could also rename it)

But when I open the url with this code nothing happens.

import urllib
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'

testfile = urllib.request.urlopen(url)

Any ideas?

Try this. Change "folder" to a folder on your machine

import os
import requests

url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'
response = requests.get(url)
with open(os.path.join("folder", "file"), 'wb') as f:
    f.write(response.content)

You can adapt an example from the docs

import urllib.request
url='https://data.toulouse-metropole.fr/api/records/1.0/download/?dataset=dechets-menagers-et-assimiles-collectes'

with urllib.request.urlopen(url) as testfile, open('dataset.csv', 'w') as f:
    f.write(testfile.read().decode())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM