python download file from url code example

Example 1: python download file from url

import requests


url = 'https://www.facebook.com/favicon.ico'
r = requests.get(url, allow_redirects=True)

open('facebook.ico', 'wb').write(r.content)

Example 2: download pdf from url python

import urllib.request
pdf_path = ""
def download_file(download_url, filename):
    response = urllib.request.urlopen(download_url)    
    file = open(filename + ".pdf", 'wb')
    file.write(response.read())
    file.close()
 
download_file(pdf_path, "Test")

Example 3: python download image from url

import urllib.request
imgURL = "http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg"

urllib.request.urlretrieve(imgURL, "D:/abc/image/local-filename.jpg")

Example 4: how to download file from python

import wget

url = "https://www.python.org/static/img/[email protected]"

wget.download(url, 'c:/users/LikeGeeks/downloads/pythonLogo.png')

Example 5: save a text file from web python

import urllib2response = urllib2.urlopen('https://wordpress.org/plugins/about/readme.txt')data = response.read()print(data)

Example 6: python get an online file

import urllib2  # the lib that handles the url stuff

data = urllib2.urlopen(target_url) # it's a file like object and works just like a file
for line in data: # files are iterable
    print line