下午好。
我想知道如何在Python中将文件或文件夹引用到变量。
假设我有一些名称如下的文件:
161225_file1.txt
161225_file2.txt
161225_file3.txt
161226_file1.txt
161226_file2.txt
161226_file3.txt
161227_file1.txt
161227_file2.txt
161227_file3.txt
我想将这些文件分配给变量,以便我可以在我拥有的电子邮件脚本中使用它,我也只需要具有特定日期的文件。
现在我只有以下内容:
#!/usr/bin/env python
###############################
#Imports (some library imports)
###############################
import sys
import time
import os
import re
from datetime import date,timedelta
from lib.osp import Connection
from lib.sendmail import *
###############################
#Parameters (some parameters i`ll use to send the email, like the email body message with yesterdays date)
###############################
ndays = 1
yesterday = date.today() - timedelta(days=ndays)
address = 'some.email@gmail.com'
title = '"Email Test %s"' % yesterday
attachments = ''
mail_body = "This is a random message with yesterday`s date %s" % yesterday
###############################
#Paths (Path that contain the home directory and the directory of the files i want to attach)
###############################
homedir = '/FILES/user/emails/'
filesdir = '/FILES/user/emails/TestFolder/'
###############################
#Script
###############################
#starts the mail function
start_mail()
#whatever message enters here will be in the email`s body.
write_mail(mail_body)
#gets everything you did before this step and sends it vial email.
send_mail(address,title,attachments)
答案 0 :(得分:0)
os.listdir()将获取目录中的文件和子目录。
如果您只想要文件,请使用os.path:
from os import listdir
from os.path import isfile, join
files = [f for f in listdir(homedir) if isfile(join(homedir, f))]
您可以找到有关如何将文件附加到电子邮件here的详细说明 感谢Oli
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None,
server="127.0.0.1"):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()