在Python3中,当我将.csv文件作为附件发送时,它缺少行

2024-05-08 20:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python脚本,可以查询一些系统,然后将结果附加到CSV文件中。此脚本每周运行一次,然后作为最后一步向CSV文件发送电子邮件。但是,当我打开附件时,我会得到上一次运行的信息,而不是当前运行的信息。我可以转到运行脚本的计算机,查看文件是否实际包含当前信息

以下是片段: 文件打开:

out_exists = os.path.isfile('/depot/sgcap/grid_capacities.csv')
if out_exists:
        out = open("/depot/sgcap/grid_capacities.csv","a")
else:
        out = open("/depot/sgcap/grid_capacities.csv","a")
        out.write(('Date,Site,Installed Capacity (TB),Used Capacity (TB)'))

文件写入和关闭:

                        out.write('\n'+ str(date) + "," + str(s) + ',' + str(xisc_tb) + ',' + str(xusc_tb))


        else:
                print('\n Errored on http request with status ', response.status_code)
out.close

最后是电子邮件部分(不知羞耻地被盗):

#bundle it up and send the email
email = 'root@a.machine.com'
password = ''
send_to_email = ['some.guy@wherever.com','another.guy@wherever.com']
subject = 'StorageGRID Capacities'
message = 'This morning\'s capacity report'
file_location = ('/depot/sgcap/grid_capacities.csv')

msg = MIMEMultipart()
msg['From'] = email
msg['To'] =  ", ".join(send_to_email)
msg['Subject'] = subject

msg.attach(MIMEText(message, 'plain'))

# Setup the attachment
filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

# Attach the attachment to the MIMEMultipart object
msg.attach(part)

server = smtplib.SMTP('my.mailserver.com', 25)
#server.starttls()
#server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()

Tags: 文件csvthesendattachmentserveremailmsg
1条回答
网友
1楼 · 发布于 2024-05-08 20:29:52

在发送文件之前,必须将写操作刷新到磁盘。在此之前,它们是缓冲的,尚未写入磁盘上的文件

刷新的最佳实践只是确保关闭文件句柄,正如Tanja Bayer所指出的,使用out.close()或更好的实践,通过open ... as使用上下文管理器

在一些不太常见的情况下,您可能希望直接调用out.flush(),但对于需要长时间打开文件的长时间运行的流程来说,这是一个不同的用例

简短回答:对于普通/小型文件写入,只需关闭文件句柄即可将数据写入磁盘

相关问题 更多 >