脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现的txt文件去重功能示例

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

2021-03-14 00:07人饭子 Python

这篇文章主要介绍了Python实现的txt文件去重功能,涉及Python针对txt文本文件的读写、字符串遍历、判断相关操作技巧,需要的朋友可以参考下

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- 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.zzvips.com
www.baidu.com
www.sina.com.cn
www.zzvips.com
www.google.com
www.sohu.com
www.zzvips.com
www.163.com

运行后new.txt内容如下:

www.zzvips.com
www.baidu.com
www.sina.com.cn
www.google.com
www.sohu.com
www.163.com

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/sinat_35360663/article/details/80414699

延伸 · 阅读

精彩推荐