python - Printing non-matching (unique) lines in a file -


i'm trying create function opens file (filename), prints each line of text differs previous line (with first line written). each output line should prefixed line number in input file.

i've come following, consistently prints last line of text regardless of whether or not duplicate line:

def squeeze(filename):     file = open(filename, 'r')     prevline = ''     line_num = 0     line in file:         line_num = line_num + 1         if line != prevline:                print ('%3d - %s'%(line_num, line))           prevline = line  filename = 'test.txt' squeeze(filename) 

i can't seem figure out , flaw in code fix this?

thank you, helpful, used ticked one!

each line should terminated in newline character \n or \r\n. final line doesn't have it.

you can use str.strip() remove it.

with open(filename, 'r') input_f:     prevline = ''     line_num = 0      line in input_f:         line_num += 1         if line.strip() != prevline.strip():     # use strip()             print('%3d - %s' % (line_num, line))          prevline = line 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -