我有一项日常任务非常适合自动化,因此我决定将其用作学习 Python 的项目。我需要做的是将一些 .xlsx 文件转换为 .csv,然后将每个文件通过电子邮件发送到特定的电子邮件地址。下面是我所得到的,直到接近结束时它都工作得很好。我希望它在发送后删除 csv 副本。File1.csv 被删除,但 file2.csv 没有被删除,因为它仍在另一个进程中打开。PermissionError: [WinError 32] 该进程无法访问该文件,因为该文件正在被另一个进程使用:“C:\Drop\file2.csv”所以很明显 csv 需要关闭,但我无法弄清楚哪个进程打开了它以及如何关闭它。import osfrom datetime import datetimeimport pandas as pdimport smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email import encodersfiles = []drop_path = 'C:\\Data Drop\\'path = os.chdir(drop_path)datestamp = datetime.now().strftime(' (%m-%d-%Y)')#Make a CSV copy of each filefor c in os.listdir(path): file_name, file_ext = os.path.splitext(c) xlsx = pd.read_excel(file_name+file_ext) xlsx.to_csv(file_name+'.csv', encoding='utf-8') files.append(file_name+'.csv')print('CSV copies created\n')#Send to appropriate email addressesrecipient = ''for s in files: print('Sending ',s) if s == 'file1.csv': recipient = '<email1@gmail.com>' elif s == 'file2.csv': recipient = '<email2@gmail.com>' email_user = 'sender@gmail.com' email_password = 'password' email_send = recipient msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = "Data transmittal" body = 'Data transmittal attached' msg.attach(MIMEText(body,'plain')) attached_file = s attachment = open(attached_file,'rb') part = MIMEBase('application','octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition',"attachment; filename= "+attached_file) msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com',587) server.starttls() server.login(email_user,email_password) server.sendmail(email_user,email_send,text) print(s,'sent.\n') server.quit()
1 回答
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
红糖糍粑
TA贡献1815条经验 获得超6个赞
您的错误是打开attachment
但从未关闭它。
代替 :attachment = open(attached_file,'rb')
使用with open()
上下文管理器:
with open(attached_file,'rb') as attachment:
part = MIMEBase('application','octet-stream')
part.set_payload((attachment).read())
# here attachment is closed automatically
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+attached_file)
添加回答
举报
0/150
提交
取消