本篇文章为大家展示了使用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怎么删除文件中的重复字段,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。