四时宝库

程序员的知识宝库

Python上传下载(python ftp上传下载)

使用Python上传和下载文件可以使用Python的内置库urllib或requests。下面是使用requests库的示例代码:### 上传文件

import requests

url = 'http://example.com/upload'

file_path = '/path/to/file'

headers = {'Authorization': 'Bearer [TOKEN]'}

with open(file_path, 'rb') as f:

response = requests.post(url, headers=headers, files={'file': f})

print(response.json())

其中,`url`是上传文件的URL地址,`file_path`是需要上传的文件路径,`headers`是HTTP请求头部,`files`参数指定要上传的文件。

### 下载文件

import requests

url = 'http://example.com/download'

file_path = '/path/to/save/file'

headers = {'Authorization': 'Bearer [TOKEN]'}

response = requests.get(url, headers=headers)

if response.status_code == 200:

with open(file_path, 'wb') as f:

f.write(response.content)


print('File downloaded successfully!')


其中,`url`是下载文件的URL地址,`file_path`是文件保存路径,`headers`是HTTP请求头部,调用`requests.get()`方法执行下载操作,然后使用`with open()`创建文件,并将响应内容写入到文件中。下载完成后打印成功信息即可。


注意,上述代码中的`[TOKEN]`是需要替换为实际的token值。此外还可以根据需要设置其他的HTTP请求参数,如超时时间等。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接