我是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 )
答案 0 :(得分:1)
通常,我不希望同时读取和写入文件。所以这就是我要做的:
这将有效删除所有经过测试的邮件。
代码可能看起来像这样:
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')