How to download file using Python?

10,616

Solution 1

You can use the urlretrieve to download the file

EX:

u = "https://publicwww.com/websites/%22google.com%22/?export=csv"

import urllib
urllib.request.urlretrieve (u, "Ktest.csv")

Solution 2

You can also download a file using requests module in python.

import shutil

import requests

url = "https://publicwww.com/websites/%22google.com%22/?export=csv"
response = requests.get(url, stream=True)
with open('file.csv', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response

Solution 3

import os
os.system("wget https://publicwww.com/websites/%22google.com%22/?export=csv")

You could try wget, if you have it.

Share:
10,616
Alex
Author by

Alex

Updated on June 14, 2022

Comments

  • Alex
    Alex almost 2 years

    I'm completely new to Python, I want to download a file by sending a request to the server. When I type it into my browser, I see the CSV file is downloaded, but when I try sending a get request it does not return anything. for example:

    import urllib2
    response = urllib2.urlopen('https://publicwww.com/websites/%22google.com%22/?export=csv')
    data = response.read()
    print 'data: ',  data
    

    It does not show anything, how can I handle that? When I search on the web, all the questions are about how to send a get request. I can send the get request, but I have no idea of how the file can be downloaded as it is not in the response of the request.

    I do not have any idea of how to find a solution for that.

  • Ubdus Samad
    Ubdus Samad about 6 years
    Please don't down-vote without providing a reason, i see two down-votes and not a single reason for it.
  • jschreiner
    jschreiner about 4 years
    I downvote this because the question asks how to do it in Python. Calling out to the os and running another executable is not "in Python". Have a look at @Rakesh's answer to see how it's done using the urllib library.
  • Louis Yang
    Louis Yang over 3 years
    This doesn't work on Windows.