本文實例講述了Python實現的txt文件去重功能。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*-#! python2import shutila=0readDir = "/Users/Administrator/Desktop/old.txt" #oldwriteDir = "/Users/Administrator/Desktop/new.txt" #new# txtDir = "/home/Administrator/Desktop/1"lines_seen = set()outfile = open(writeDir, "w")f = open(readDir, "r")for line in f: if line not in lines_seen: a+=1 outfile.write(line) lines_seen.add(line) print(a) print('/n')outfile.close()print("success")
其中old.tx如下:
www.jb51.net
www.baidu.com
www.sina.com.cn
www.jb51.net
www.google.com
www.sohu.com
www.jb51.net
www.163.com
運行后new.txt內容如下:
www.jb51.net
www.baidu.com
www.sina.com.cn
www.google.com
www.sohu.com
www.163.com
PS:這里再為大家提供幾款相關工具供大家參考使用:
在線去除重復項工具:
http://tools.jb51.net/code/quchong
在線文本去重復工具:
http://tools.jb51.net/aideddesign/txt_quchong
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答