温馨提示×

python文件怎么上传下载

小樊
120
2024-11-16 18:27:46
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

要在Python中实现文件的上传和下载,可以使用requests库。首先确保已经安装了requests库,如果没有安装,可以使用以下命令进行安装:

pip install requests

文件上传

以下是一个简单的文件上传示例:

import requests

url = 'https://example.com/upload'  # 替换为目标URL
file_path = 'path/to/your/file.txt'  # 替换为要上传的文件路径

with open(file_path, 'rb') as file:
    files = {'file': (file.name, file)}
    response = requests.post(url, files=files)

print(response.text)

文件下载

以下是一个简单的文件下载示例:

import requests

url = 'https://example.com/download'  # 替换为目标URL
file_path = 'path/to/save/downloaded_file.txt'  # 替换为要保存的文件路径

response = requests.get(url)

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

print('文件下载完成')

请注意,这些示例仅用于演示目的。在实际应用中,您需要根据目标服务的要求进行相应的调整,例如设置请求头、处理异常等。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:jfinal怎样实现文件上传下载

0