如何使用python在文件名中使用通配符将文件附加到电子邮件

2024-10-04 05:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想发送电子邮件与附加的jpg文件时,它被创建,然后删除该文件,在文件夹中没有留下任何jpg文件。文件的实际名称会随着日期和时间而改变,但我不知道它是什么。我试过用这个

#Email body
rstime = datetime.datetime.now().strftime('%d %b %Y at %H:%M:%S')
body = 'Picture saved of movement at front of house ' + str(rstime)

msg.attach(MIMEText(body, 'plain'))
fp = open('/mnt/usb/motion/*.jpg', 'rb')
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

#remove file after emailing
os.remove('/mnt/usb/motion/*.jpg')

这给了我一个错误- IOError:[Errno 2]没有这样的文件或目录:'/mnt/usb/motion/*.jpg'

我的代码怎么了?如果我输入文件名,它可以工作,但我想使用通配符。你知道吗


Tags: 文件ofimgdatetimebodymsgremoveat
2条回答

看看fnmatch

import fnmatch
import os

files = {}
working_dir = '/mnt/usb/motion/'

for filename in fnmatch.filter(os.listdir(working_dir), '*jpg'):
    filepath = os.path.join(working_dir, filename)
    files[filename] = open(filepath).read()
    os.remove(filepath)

但是glob模块看起来更好,因为在本例中不必join文件路径和文件名。你知道吗

不能以这种方式使用通配符。如果两个文件匹配通配符,会发生什么情况?两个文件应该在同一个对象中打开吗?你知道吗

您可以将通配符与pythonglob模块一起使用:

import glob
# Email body
rstime = datetime.datetime.now().strftime('%d %b %Y at %H:%M:%S')
body = 'Picture saved of movement at front of house ' + str(rstime)

msg.attach(MIMEText(body, 'plain'))
files = glob.glob("/mnt/usb/motion/*.jpg")
firstFile = files[0]
fp = open(firstFile, "rb");
img = MIMEImage(fp.read())
fp.close()
msg.attach(img)

# remove file after emailing
os.remove(firstFile)

相关问题 更多 >