【问题标题】:Is there a better way to write information from a for loop to .txt file?有没有更好的方法将信息从 for 循环写入 .txt 文件?
【发布时间】:2020-01-30 09:34:15
【问题描述】:

我正在构建一个 URL 检查器,它会找到我给它的损坏的 URL,然后将结果发送给我的电子邮件。这是我的最终结果。我必须在我的 for 循环中创建另一个要写入的文件,然后发送该文件。它可以工作,但是有没有更简洁的方法可以做到这一点,并且没有两个 .txt 文件,并且不会覆盖原始 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()

【问题讨论】:

    标签: python testing automated-tests


    【解决方案1】:

    这部分:

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

    可以这样简单地完成:

    with open("listurls.txt", "w") as f:       
        f.writelines(error+ "\n")               # Write the new data
    

    注意,如果您使用的是with open(...),则不需要f.close()

    话虽如此,我不明白你为什么需要为每个 URL 覆盖这个文件,更合理的方法是记录所有损坏的 URL,而不仅仅是最后一个(你覆盖了文件,记得吗?),并在您的电子邮件中包含所有损坏的链接。

    另一个改进是只提供网站的根 URL,并递归地提取页面并自动收集所有链接。不过,不确定这是否是您所需要的。

    【讨论】:

    • 我最终使用 with open("listurls.txt", "w") as f: f.truncate(0) 在我的代码之前,然后我使用 append 而不是 open 的 "w" ("listurls.txt", "a") as f:
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2011-04-12
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多