no comments yet
02 Sep 2014

python TXT列表去重

那天要试试邮件群发,需要采集多个页面的邮箱并按每个邮箱一行逐行写入到txt里,为了防止有重复的邮箱导致重复发送邮件,使用以下代码可以轻松实现txt文本列表去重甚至排序功能。

#coding=utf-8 
import os


def open_txt():  #打开TXT文本写入数组 
    if os.path.exists('0.txt'):
        try: 
            xxx = file(r'0.txt', 'r') 
            for xxx_line in xxx.readlines(): 
                passlist.append(xxx_line) 
            xxx.close() 
        except: 
            return 0     
    else:
        print "Sorry, I cannotSorry, I cannot find theSorry, I cannot find theSorry, I cannot find theSorry, I cannot find theSorry, I cannot find theSorry, I cannot find theSorry, I cannot find the find the file."  
        exit()     
def write_txt():  #将排好序的数组写入TXT文本 

    try: 
        yyy = file(r'before.txt', 'w') 
        for i in list_passwed: 
            yyy.write(i) 
        yyy.close() 
    except: 
        return 0


global  passlist  #声明全局变量 
passlist = []    #用户名 
open_txt()   #TXT导入数组 
#passlist = list(set(passlist))   #python 列表去重 
global  list_passwed  #列表去重,不打乱原来的顺序 
list_passwed=[] 
for i in passlist: 
    if i not in list_passwed: 
        list_passwed.append(i) 
write_txt()
print "Success."  

set方法可以直接去重而且还会排序,如果需要排序的话用set是最快的~