Displaying a File without Adjacent Duplicates in Python

I'm trying to write a file that displays a text file So I want the program to display the file while it removes any adjacent identical lines. My question is that the code isn't working since I know I'm missing something and I was wondering how write the lines for this problem I'm facing?

input

1 
1 
2 
2 
1 
3 
1 
1 
1


then the output should be:
1 
2 
1 
3 
1

The code I have written right now is:

lines = open('list.txt', 'r').readlines()

lines_set = set(lines)

out  = open('list.txt', 'w')

for line in lines_set:
    out.write(line)

print(set(f.readlines()))

Answers


As mentioned in a comment to the question, set() is not what you want because it will remove all duplicates, not just adjacent duplicates. You need something more like this:

with open(r'C:\Users\Gord\Desktop\list_in.txt', 'r') as f_in:
    lines = f_in.readlines()

with open(r'C:\Users\Gord\Desktop\list_out.txt', 'w') as f_out:
    prev_line = ''
    for line in lines:
        if line != prev_line:
            f_out.write(line)
            prev_line = line

with open(r'C:\Users\Gord\Desktop\list_out.txt', 'r') as f:
    for line in f.readlines():
        print(line),

Need Your Help

what is the best way to build downloadable store cards for mobile site?

php mobile

I want to create a downloadable digital membership card(e.g card which we use at store after purchasing but these are physical cards. i am talking about digital cards) for my custom based php frame...

Website. AJAX and FIREFOX problems. I dont think Firefox likes ajax..?

php javascript mysql ajax

Working on an AJAX website (HTML,CSS,JavaScript, AJAX, PHP, MySQL).