我想在创建时发送附带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'
我的代码出了什么问题?如果我输入文件名它可以工作,但我想使用通配符。
答案 0 :(得分:0)
您不能以这种方式使用通配符。如果两个文件与通配符匹配,会发生什么?两个文件应该在同一个对象中打开吗?
您可以使用通配符,例如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)
答案 1 :(得分:0)
查看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
文件路径和文件名。