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

How to use wildcards in filename to attach file to email using 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'

我的代码有什么问题?如果我输入文件名,它可以工作,但我想使用通配符。

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

您可以使用通配符,例如python glob 模块:

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)

看看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 文件路径和文件名。