mercredi 29 janvier 2020

Is there a better way to write information from a for loop to .txt file?

I'm building a URL Checker that finds broken URLS that I give it then sends an email to me with the results. This is my end result. I had to create another file to write to inside of my for loop then send that file. It works but is there a cleaner way to do this and not have two .txt files and not overwrite what is in the original testurls.txt?

import requests
import smtplib
from email.message import EmailMessage


with open ("testurls.txt", "r") as txt_file:
    for urls in txt_file:
        request = requests.get(urls)
        try:
            request.raise_for_status()
        except Exception as error:
            error = 'There was a problem: %s' % (error)

            with open("listurls.txt", "r+") as f:       
                f.truncate(0)                           #Deletes the files pre existing data
                f.writelines(error+ "\n")               #Writes the new data
            f.close()
        else:
            pass
with open("listurls.txt", "r") as file_to_send:
    msg = EmailMessage()
    msg.set_content(file_to_send.read())

msg['Subject'] = "Here are the list of URLs that don't work"
msg['From'] = 'andrewtalbotprogramming@gmail.com'
msg['To'] = 'andrewtalbotprogramming@gmail.com'

s = smtplib.SMTP_SSL(host='smtp.gmail.com', port=465)
print("Enter Your Password To Continue")
password = input('')
s.login('andrewtalbotprogramming@gmail.com',password)

s.send_message(msg)
s.quit()

Aucun commentaire:

Enregistrer un commentaire