Home > Article > Backend Development > How to Download Files from a Web Server in Python 3?
Downloading files from a web server is a common task in many programming projects. Python provides several libraries to simplify this process, making it easy to download files from specified URLs.
<code class="python">import urllib.request url = "http://example.com/file.jar" urllib.request.urlretrieve(url, "file.jar")</code>
This code uses the urlretrieve function to download the file from url and save it locally as file.jar.
<code class="python">import urllib.request import shutil url = "http://example.com/file.jar" with urllib.request.urlopen(url) as response, open("file.jar", "wb") as out_file: shutil.copyfileobj(response, out_file)</code>
This code opens a file-like object using the urlopen function and copies the content to a local file using shutil.copyfileobj. This method allows for streaming of large files without storing the entire file in memory.
<code class="python">import urllib.request import gzip url = "http://example.com/file.gz" with urllib.request.urlopen(url) as response: with gzip.GzipFile(fileobj=response) as uncompressed: data = uncompressed.read()</code>
This code opens a compressed file as a file-like object using the gzip.GzipFile class and reads the decompressed data into a variable.
The above is the detailed content of How to Download Files from a Web Server in Python 3?. For more information, please follow other related articles on the PHP Chinese website!