python如何删除文件中重复的字段

yipeiwu_com5年前Python基础

本文实例为大家分享了python如何删除文件中重复字段的具体代码,供大家参考,具体内容如下

原文件内容放在list中,新文件内容按行查找,如果没有出现在list中则写入第三个文件中。

import csv

filetxt1 = 'E:/gg/log/log1.txt'
filecsv1 = 'E:/gg/log/log1.csv'
filecsv2 = 'E:/gg/log/log2.csv'
filecsv3 = 'E:/gg/log/log3.csv'


class operFileCsv():
 def __init__(self, filename=None):
  self.filename = filename

 def readCsvFile(self):
  readCsvHandler = open(self.filename, 'r')
  filelines = csv.reader(readCsvHandler, dialect='excel')
  for fileline in filelines:
   print(fileline)
  readCsvHandler.close

 def writeCsvFile(self, writeline):
  writeCsvHandler = open(self.filename, 'a', newline='')
  csvWrite = csv.writer(writeCsvHandler, dialect='excel', )
  csvWrite.writerow(writeline)
  writeCsvHandler.close()


class getLogBuffFromFile():
 def __init__(self):
  self.logBuff1 = []

 def getLog1Buff(self, filename):
  with open(filename) as filehandler:
   while True:
    logOneLine = filehandler.readline().strip()
    if not logOneLine:
     break
    self.logBuff1.append(logOneLine)
  # print('TRACE: The log1 has ', len(self.logBuff1), ' lines.')
  return self.logBuff1

 def getLog2Buff(self, logOneLine):
  pass


class deleteIterantLog():
 def __init__(self):
  self.logBuff1List = None
  self.logBuff2OneLine = None

 def deleteProcedure(self, oldlog, newlog, createlog):
  self.logBuff1List = getLogBuffFromFile().getLog1Buff(oldlog)
  self.dealProcedure(newlog, createlog)

 def dealProcedure(self, file1name, file2name):
  with open(file1name, 'r') as readCsvHandler:
   filelines = csv.reader(readCsvHandler, dialect='excel')
   for fileline in filelines:
    if fileline[1] not in self.logBuff1List:
     operFileCsv(file2name).writeCsvFile(fileline)


if __name__ == '__main__':
 deleteIterantLog().deleteProcedure(filetxt1, filecsv2, filecsv3)

小编再为大家分享一段Python用集合把文本中重复的字去掉的方法:

import os,sys,datetime
import codecs
with open('aaaaa.txt', 'r') as f:  #读入文本中的文件
 l = f.readlines() # txt中所有字符串读入data
 x=set(l[0])
 for i in range(1,len(l)):
  x.update(l[i])
 s="".join(list(x))
 print(s)
with open('result.txt','wb') as f1: #把结果写到文件result中
 b=bytes(s,encoding="utf-8") 
 f1.write(b)

更多关于python安装教程的文章请参考《python各版本安装教程》

更多精彩书单,请点击python编程必备书单

领取干货:零基础入门学习python视频教程

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

flask 使用 flask_apscheduler 做定时循环任务的实现

我是初学者,对 flask 很陌生,网上搜到的文章都看不懂,很尴尬。 本意是打算对广发信用卡diy卡积分兑换签帐额的数量进行爬虫监控。将抓取到的余量通过钉钉机器人发送到群里。爬虫代码就...

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...

按日期打印Python的Tornado框架中的日志的方法

网站流量上来后,日志按天甚至小时存储更方便查看和管理,而Python的logging模块也提供了TimedRotatingFileHandler来支持以不同的时间维度归档日志。 然而根据...

详解python中asyncio模块

一直对asyncio这个库比较感兴趣,毕竟这是官网也非常推荐的一个实现高并发的一个模块,python也是在python 3.4中引入了协程的概念。也通过这次整理更加深刻理解这个模块的使用...

解决pyqt中ui编译成窗体.py中文乱码的问题

我在Eric工具下编译的 解决办法: 1、打开 C:\Python27\Lib\site-packages\eric4\i18n,将中文资源包的名称"GB2312."去掉,变成eric4...