python 高效文件传输
时间: 2023-11-22 21:48:25 浏览: 37
以下是使用Python进行高效文件传输的一种方法:
1.使用requests库进行文件上传和下载
```python
import requests
# 文件上传
url = 'http://example.com/upload'
files = {'file': open('example.txt', 'rb')}
response = requests.post(url, files=files)
# 文件下载
url = 'http://example.com/download'
response = requests.get(url)
with open('example.txt', 'wb') as f:
f.write(response.content)
```
2.使用socket库进行文件传输
```python
import socket
# 文件上传
HOST = '127.0.0.1'
PORT = 8000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
with open('example.txt', 'rb') as f:
data = f.read()
s.sendall(data)
# 文件下载
HOST = '127.0.0.1'
PORT = 8000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
with open('example.txt', 'wb') as f:
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
```
3.使用paramiko库进行文件传输(支持SSH协议)
```python
import paramiko
# 文件上传
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='username', password='password')
sftp = ssh.open_sftp()
sftp.put('example.txt', '/remote/path/example.txt')
sftp.close()
ssh.close()
# 文件下载
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='username', password='password')
sftp = ssh.open_sftp()
sftp.get('/remote/path/example.txt', 'example.txt')
sftp.close()
ssh.close()
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)