python简单的实现文件内容去重

文件去重

这里主要用的是set()函数,特别地,set中的元素是无序的,并且重复元素在set中自动被过滤。

测试文本为   data.txt

在这里插入图片描述

具体代码如下:
// 文件去重
#!/usr/bin/env python 
# -*- coding:utf-8 -*-
# 
# author  g7y12
#

file_list = []  #创建一个空列表
def out_file():
    #file_2 = open_file()
    file = "data.txt"    #打开需要去重的文件
    with open(file, "r", encoding="utf-8") as f:
        file_2 = f.readlines()
        for file in file_2:
            file_list.append(file)
        out_file1 = set(file_list)    #set()函数可以自动过滤掉重复元素
        last_out_file = list(out_file1)
        for out in last_out_file:
            with open("result.txt","a+",encoding="utf-8") as f:   #去重后文件写入文件里
                f.write(out+"\n")
                print(out)

if __name__ =="__main__":
    out_file()
   运行后结果

在这里插入图片描述
小结:set()去重后,元素顺序变了,如果文件不考虑去重后的顺序的话,可以用此种方法,简单快捷

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值