In Python 3 when I send a .csv file as an attachment it is missing lines

Andrew Madsen

I have a python script that queries some systems and then appends the results to a CSV file. This script runs once a week and then emails the CSV file as the last step. However when I open the attachment I get the information on the previous run but not the information from the current run.I can go to the machine running the script and see that the file actually has the current information.

Here are snippets: File Open:

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)'))

File write and close:

                        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

And lastly the email portion (shamelessly stolen):

#bundle it up and send the email
email = '[email protected]'
password = ''
send_to_email = ['[email protected]','[email protected]']
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()
Chris Johnson

Your writes must be flushed to disk before you send the file. Before that, they are buffered and have NOT been written to the file on disk.

Best practice for flushing is simply to ensure the file handle is closed, as Tanja Bayer notes, either using out.close() or better practice, using a context manager via open ... as.

There are less common cases where you might want to call out.flush() directly but those are a different use case, for long-running processes that need to keep files open for a long time.

Short answer: for normal / small file writes, just close the file handle to write data to disk.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do I send a generated csv file as an email attachment in React

How do I send an email with a .csv attachment using Python

one extra line getting added when i open CSV file on window. This is observed only when i send CSV file as attachment to email

Python Sendgrid send email with PDF attachment file

Python cannot find file to send as email attachment

pandas .txt file to .csv file missing lines

Python 3 Read a json file with missing objects within lines

Object of type bytes is not JSON serializable when trying to send a file from S3 as an email attachment

Add missing lines in file with python

Unable to create and send dynamic CSV file as attachment over mail

How to write a new CSV file and send as Email attachment

Timestamp is missing when I export dataset to CSV file

Send mail with file attachment

I want to send file as attachment to an API POST request

Python send email with an attachment

Missing lines when reading file by Reader

Send Automated emails from python based on file attachment conditions

Send a file as attachment in objective c

PHPMailer send mail but file attachment is not with it

Java send email with file in attachment

How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3

AWS Missing credentials when i try send something to my S3 Bucket (Node.js)

Blank lines when reading CSV file in Java

Unexpected amount of lines when writing to a csv file

How to separate a CSV file when there are "" lines?

Why is my output only one row when i try outputting my dataframe to a csv file?Python3/boto3

How do I send an email alert through python if a particular string is missing in my file?

python - send email along with attachment

Python How to send an attachment with mailgun