我有一項日常任務非常適合自動化,因此我決定將其用作學習 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 = '<[email protected]>' elif s == 'file2.csv': recipient = '<[email protected]>' email_user = '[email protected]' 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 回答

紅糖糍粑
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
提交
取消