本文共 798 字,大约阅读时间需要 2 分钟。
本文实例讲述了Python实现的txt文件去重功能,分享给大家供参考。以下是具体实现代码及说明:
# -*- coding:utf-8 -*-import shutilreadDir = "/Users/Administrator/Desktop/old.txt" # 旧文件writeDir = "/Users/Administrator/Desktop/new.txt" # 新文件lines_seen = set()outfile = open(writeDir, "w")f = open(readDir, "r")for line in f: if line not in lines_seen: outfile.write(line) lines_seen.add(line)outfile.close()
代码说明:
lines_seen用于存储已处理的行示例输入文件old.txt内容如下:
www.jb51.netwww.baidu.comwww.sina.com.cnwww.jb51.netwww.google.comwww.sohu.comwww.jb51.netwww.163.com
运行后,new.txt将只包含唯一的内容:
www.jb51.netwww.baidu.comwww.sina.com.cnwww.google.comwww.sohu.comwww.163.com
希望以上内容对您有所帮助!如需了解更多Python文件操作技巧,欢迎查阅我们的专题文章。
转载地址:http://uhofk.baihongyu.com/