Klevin Kona
Klevin Kona

Reputation: 361

Read lines and remove them after read complete

I am new to python language, trying to develop a script to read a file with emails in it, split good emails from bad emails and than remove that line from the source file. I got so far but here i have no idea how to remove the line already readed

Any help?

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 ) 

Upvotes: 0

Views: 140

Answers (2)

rje
rje

Reputation: 6418

In general I would not prefer to both read and write to a file at the same time. So here is what I would do:

  • open the file for reading
  • loop over the emails and do your thing. In the comments below you've clarified you want to test only the first 100 mails, so that is what the code below now does.
  • close the file
  • reopen the file but this time in write mode, truncating it (throwing away its contents)
  • write all the remaining (untested) emails to the file

This effectively removes all mails that have been tested.

The code might look like this:

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)

Upvotes: 1

Bakuriu
Bakuriu

Reputation: 101919

You can't. That's simply not how files work, you cannot just remove a couple lines from the middle of a file. To achieve what you want you want to overwrite or replace the file.

So in your code you'd remove the original file and copy good_email.txt over it:

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

Upvotes: 1

Related Questions