Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download csv file through python (url)

Tags:

python

urllib

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?

like image 459
blabla Avatar asked Oct 29 '25 17:10

blabla


2 Answers

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)
like image 197
Kabard Avatar answered Oct 31 '25 06:10

Kabard


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())
like image 41
Paul Rooney Avatar answered Oct 31 '25 06:10

Paul Rooney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!