python - IO错误: [Errno 2] No such file or directory: '123.avi'

标签 python

我正在编写一个脚本来从树莓派 4 发送电子邮件,我想通过 python 将文件附加到电子邮件,但我总是收到此错误。

我对Python还很陌生。我知道该文件位于正确的位置,并且我尝试了其他一些文件。我尝试了文件的完整路径。我读了很多其他类似的问题,但没有运气

filename = '123.avi'
attachmet = open(filename,'rb')

part = MIMEBase('application','octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+filename)

msg.attach(part)

如果没有这行脚本,脚本可以正常工作。 我收到邮件了。

但是有了这行我得到错误:

Traceback (most recent call last):
  File "/home/pi/Monitor/sendmail.py", line 31, in <module>
    attachmet = open(filename,'rb')
IOError: [Errno 2] No such file or directory: '123.avi'

最佳答案

这对我有用。

with open(full_path_of_file, "rb") as fs:
    part = MIMEBase('application', "octet-stream")
    part.set_payload(fs.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(full_path_of_file))
msg.attach(part)

关于python - IO错误: [Errno 2] No such file or directory: '123.avi' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58524981/

相关文章:

python - 如何根据特定索引重新排列嵌套列表

python - 选择列表中最早的条目

python - 具有相同列表的两个变量具有不同的 ID.....这是为什么?

python - 如何使用Python脚本在Linux上启动应用程序?

python - Python 字典的顺序是否在迭代中得到保证?

python - Haskell 与 Python 线程模型

python - 什么决定了 Python 字典中数据的顺序?

python - Python 中的 Excel 求解器

python - 在 Pandas 图中仅隐藏轴标签,而不是整个轴

python - 有效地更新Python中列表列表中特定位置的元素