读取行并在读取完成后将其删除

时间:2018-10-15 18:31:05

标签: python python-3.x

我是python语言的新手,它试图开发一个脚本来读取其中包含电子邮件的文件,将不良电子邮件与不良电子邮件分开,然后从源文件中删除该行。 我到现在为止了,但是在这里我不知道如何删除已经读过的行

有帮助吗?

import os
with open('/home/klevin/Desktop/python_test/email.txt', 'rw+') as f:
    for line in f.readlines():
        #print line
        domain = line.split("@")[1]


        #print(domain)

        response = os.system("ping -c 1 " + domain)


        if response == 0:
            print(response)
            file1 = open("good_emails.txt","a") 
            file1.write( line ) 

        else:
            print(response)
            file = open("bad_emails.txt","a") 
            file.write( line ) 

2 个答案:

答案 0 :(得分:1)

通常,我不希望同时读取和写入文件。所以这就是我要做的:

  • 打开文件进行阅读
  • 循环查看电子邮件并执行您的操作。在下面的注释中,您已经说明只想测试前100封邮件,因此下面的代码现在可以进行测试。
  • 关闭文件
  • 重新打开文件,但这次是在写入模式下,将其截断(丢弃其内容)
  • 将所有剩余(未试用)电子邮件写入文件

这将有效删除所有经过测试的邮件。

代码可能看起来像这样:

import os

emails = []

# Opening the file for reading
with open('email.txt', 'r') as f, open("good_emails.txt", "w") as good, open("bad_emails.txt", "w") as bad:
    emails = f.readlines()

    # Only loop over the first 100 mails
    for line in emails[:100]:
        domain = line.split("@")[1]
        response = os.system("ping -c 1 " + domain)

        if response == 0:
            print(response)
            good.write( line ) 

        else:
            print(response)
            bad.write( line ) 

# Now re-open the file and overwrite it with the correct emails            
with open('email.txt', 'w') as f:
    # Write the remaining emails to the original file
    for e in emails[100:]:
        f.write(e)

答案 1 :(得分:1)

不能。这根本不是文件的工作方式,您不能仅从文件中间删除几行。要实现您想要的覆盖或替换文件。

因此,在您的代码中,您将删除原始文件并在其上复制good_email.txt

import shutil
import subprocess

with open('email.txt', 'r') as original, open("good_emails.txt", "w") as good, open("bad_emails.txt", "w") as bad:
    for line in original:  # no need to readlines()
        domain = line.split("@")[1]
        response = subprocess.call(['ping', '-c', '1', domain])
        if response == 0:
            good.write(line) 
        else:
            bad.write(line)

shutil.copyfile('good_emails.txt', 'emails.txt')