无法关闭 csv 以将其删除
Trouble closing a csv to delete it
我有一项日常任务非常适合自动化,因此我决定将其作为一个项目来学习 Python。我需要做的是将几个 .xlsx 文件转换为 .csv,然后将每个文件通过电子邮件发送到特定的电子邮件地址。
以下是我所得到的,直到快结束时它都可以正常工作。我希望它在发送后删除 csv 副本。 File1.csv 被删除但 file2.csv 没有,因为它仍在另一个进程中打开。
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Drop\file2.csv'
很明显 csv 需要关闭,但我无法弄清楚哪个进程打开了它以及如何关闭它。
import os
from datetime import datetime
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
files = []
drop_path = 'C:\Data Drop\'
path = os.chdir(drop_path)
datestamp = datetime.now().strftime(' (%m-%d-%Y)')
#Make a CSV copy of each file
for 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 addresses
recipient = ''
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()
print('All data has been sent.\n')
#Remove CSV files once sent.
for files in os.listdir(drop_path):
if files.endswith('.csv'):
os.remove(drop_path + files)
print('CSV files cleared.\n')
#Add the date to the end of each xlsx file name
for f in os.listdir(path):
file_name, file_ext = os.path.splitext(f)
if file_ext==".csv":
continue
else:
new_name = file_name+datestamp+file_ext
os.rename(f, new_name)
print('Dates added to file names.\n')
print('\nAll operations are complete.')
您的错误是打开 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)
我有一项日常任务非常适合自动化,因此我决定将其作为一个项目来学习 Python。我需要做的是将几个 .xlsx 文件转换为 .csv,然后将每个文件通过电子邮件发送到特定的电子邮件地址。
以下是我所得到的,直到快结束时它都可以正常工作。我希望它在发送后删除 csv 副本。 File1.csv 被删除但 file2.csv 没有,因为它仍在另一个进程中打开。
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Drop\file2.csv'
很明显 csv 需要关闭,但我无法弄清楚哪个进程打开了它以及如何关闭它。
import os
from datetime import datetime
import pandas as pd
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
files = []
drop_path = 'C:\Data Drop\'
path = os.chdir(drop_path)
datestamp = datetime.now().strftime(' (%m-%d-%Y)')
#Make a CSV copy of each file
for 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 addresses
recipient = ''
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()
print('All data has been sent.\n')
#Remove CSV files once sent.
for files in os.listdir(drop_path):
if files.endswith('.csv'):
os.remove(drop_path + files)
print('CSV files cleared.\n')
#Add the date to the end of each xlsx file name
for f in os.listdir(path):
file_name, file_ext = os.path.splitext(f)
if file_ext==".csv":
continue
else:
new_name = file_name+datestamp+file_ext
os.rename(f, new_name)
print('Dates added to file names.\n')
print('\nAll operations are complete.')
您的错误是打开 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)