I'm trying to create a function which opens a file (filename
), prints each line of the text which differs from the previous line (with the first line always written). Each output line should be prefixed with its line number in the input file.
I've come up with the following, which consistently prints the last line of the text regardless of whether or not it is a duplicate line:
def squeeze(filename):
file = open(filename, 'r')
prevline = ''
line_num = 0
for 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 to figure out where and what the flaw in my code is to fix this?
Thank you, all very helpful, used ticked one!
Each line should be terminated in a newline character
\n
or\r\n
. So your final line doesn't have it.You can use
str.strip()
to remove it.