深度阅读

How to Download Files from URL in Python

作者
作者
2023年08月22日
更新时间
11.08 分钟
阅读时间
0
阅读量

To download files from a URL in Python, you can use the requests module. Here is an example code snippet that demonstrates how to download a file using requests:

import requests

url = 'https://www.example.com/file.zip'
response = requests.get(url)

with open('file.zip', 'wb') as f:
    f.write(response.content)

In this example, we import the requests module and define the URL of the file we want to download. We then use the requests.get() method to retrieve the contents of the file at the specified URL.

We then open a file using the open() function with write binary mode ('wb'), and use the write() method to write the binary content of the file to the open file. Finally, we close the file.

This code will download the file at the specified URL and save it in the current working directory with the name file.zip. You can modify the code to specify a different file name or directory location.

Please note that downloading files from untrusted sources can be dangerous and potentially harmful to your computer. You should only download files from trusted sources.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。