Python如何发送文件

原创
admin 3小时前 阅读数 9 #Python

Python发送文件的方法

Python中,可以通过多种方式发送文件,下面介绍了几种常见的方法。

使用电子邮件发送文件

可以使用Python内置的smtplibemail模块来发送邮件,其中可以包含文件作为附件,下面是一个简单的示例代码:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
创建一个MIMEMultipart对象
msg = MIMEMultipart()
设置邮件的标题和发送者、接收者
msg['Subject'] = '发送文件'
msg['From'] = 'sender@python1991.cn'
msg['To'] = 'receiver@python1991.cn'
添加文件作为附件
with open('example.txt', 'rb') as f:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(f.read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= example.txt")
    msg.attach(part)
发送邮件
with smtplib.SMTP('smtp.python1991.cn') as server:
    server.login('sender@python1991.cn', 'password')
    server.sendmail(msg['From'], msg['To'], msg.as_string())

使用FTP发送文件

可以通过FTP协议将文件发送到指定的FTP服务器上,下面是一个使用Python内置的ftplib模块来发送文件的示例代码:

from ftplib import FTP
创建FTP对象并连接到服务器
ftp = FTP('ftp.python1991.cn')
ftp.login('username', 'password')
切换到目标目录
ftp.cwd('/target/directory')
发送文件
with open('example.txt', 'rb') as f:
    ftp.storbinary('STOR example.txt', f)
关闭连接
ftp.quit()

使用HTTP发送文件

可以通过HTTP协议将文件发送到指定的服务器上,下面是一个使用Python内置的requests模块来发送文件的示例代码:

import requests
设置要发送的文件和URL
file = 'example.txt'
url = 'http://python1991.cn/upload'
发送文件并打印响应结果
response = requests.post(url, files={file: open(file, 'rb')})
print(response.text)
热门