Имам нужда от моя код за премахване на дублиращи се редове от файл, в момента той просто възпроизвежда същия файл като изход. Може ли някой да види как да поправя това? За цикълът не работи, както бих искал.
#!usr/bin/python
import os
import sys
#Reading Input file
f = open(sys.argv[1]).readlines()
#printing no of lines in the input file
print "Total lines in the input file",len(f)
#temporary dictionary to store the unique records/rows
temp = {}
#counter to count unique items
count = 0
for i in range(0,9057,1):
if i not in temp: #if row is not there in dictionary i.e it is unique so store it into a dictionary
temp[f[i]] = 1;
count += 1
else: #if exact row is there then print duplicate record and dont store that
print "Duplicate Records",f[i]
continue;
#once all the records are read print how many unique records are there
#u can print all unique records by printing temp
print "Unique records",count,len(temp)
#f = open("C://Python27//Vendor Heat Map Test 31072015.csv", "w")
#print f
#f.close()
nf = open("C://Python34//Unique_Data.csv", "w")
for data in temp.keys():
nf.write(data)
nf.close()
# Written by Gary O"Neill
# Date 03-08-15
Отговори:
3 за отговор № 1Това е много по-добър начин да направите това, което искате:
infile_path = "infile.csv"
outfile_path = "outfile.csv"
written_lines = set()
with open(infile_path, "r") as infile, open(outfile_path, "w") as outfile:
for line in infile:
if line not in written_lines:
outfile.write(line)
written_lines.add(line)
else:
print "Duplicate record: {}".format(line)
print "{} unique records".format(len(written_lines))
Това ще прочете по един ред в даден момент, така че работи дори и на големи файлове, които не се вписват в паметта. written_lines
така или иначе ще е по-голям, отколкото да има две копия на почти всеки ред в паметта.
1 за отговор № 2
Трябва да тествате съществуването на f[i]
в temp
не i
, Промяна на реда:
if i not in temp:
с
if f[i] not in temp: