Python实现的txt文件去重功能示例

yipeiwu_com5年前Python基础

本文实例讲述了Python实现的txt文件去重功能。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#! python2
import shutil
a=0
readDir = "/Users/Administrator/Desktop/old.txt"  #old
writeDir = "/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程序设计有所帮助。

相关文章

python正则表达式match和search用法实例

本文实例讲述了python正则表达式match和search用法。分享给大家供大家参考。具体分析如下: python提供了2中主要的正则表达式操作:re.match 和 re.searc...

python求素数示例分享

复制代码 代码如下:# 判断是否是素数def is_sushu(num): res=True for x in range(2,num-1):  ...

Python队列的定义与使用方法示例

Python队列的定义与使用方法示例

本文实例讲述了Python队列的定义与使用方法。分享给大家供大家参考,具体如下: 虽然Python有自己的队列模块,我们只需要在使用时引入该模块就行,但是为了更好的理解队列,自己将队列实...

寻找网站后台地址的python脚本

#!/usr/bin/python # This was written for educational purpose only. Use it at your own risk...

Python实现微信中找回好友、群聊用户撤回的消息功能示例

本文实例讲述了Python实现微信中找回好友、群聊用户撤回的消息功能。分享给大家供大家参考,具体如下: 还在好奇好友撤回了什么消息吗?群里撤回了什么消息?下面的代码实现了:即使群、好友撤...