Python How To Download A File From Url
Python is useful for automating all sorts of things. One of the things that you can do with it is download a file from a URL. This can be done fairly easily with only a few lines of code ( potentially even just one line ).
We are going to assume that you are using Python 3 because that is what we tested with and really everybody should be using it at this point. Some libraries and functions are different between Python 2 and 3.
In Python you can download a file using the requests library like this. It basically consists of two steps. First we download the file data which is stored in a variable. Second we write the contents to a file.
import requests x = 'https://www.python.org/static/img/python-logo.png' r = requests.get(x) with open('logo.png', 'wb') as f: f.write(r.content)
We can also use the wget library to download files. In this example we do the same thing as above except that we use fewer lines of code. It could just as easily be done with a single line of code. Downloading and writing to a file are done in a single step.
import wget x = 'https://www.python.org/static/img/python-logo.png' wget.download(x, 'logo.png')
You might need to download and install the wget module first. You can do that like this.
pip3 install wget