您好,登錄后才能下訂單哦!
本篇文章為大家展示了使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。