Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python read content of txt file, save each line as a different string in a list and read these lists to find duplicates

I’m kinda new to pythin, and
I’m trying to make my python read 2 different .txt files, write what’s inside in a list and compare both lists to find and delete duplicates. But I found out that it didn’t write anything in my lists.
Here is my code:

import os
dir = os.listdir
T = "Albums"
if T not in dir():
    os.mkdir("Albums")
with open('list.txt','w+') as f:
    linesA = f.readlines()
    print(linesA)
with open('completed.txt','w+') as t:
    linesB = t.readlines()
    print(linesB)
for i in linesA[:]:
    if i in linesB:
        linesA.remove(i)
print(linesA)
print(linesB)

I tried the code above. In list.txt I wrote (on separate lines) A, B and C. In completed.txt, I wrote (also on separate lines) A and B. It should have first ouptutted the content of the lists, which were empty for some reasons.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Does this help:

  • I suggest using not os.path.exists(entry) instead of not entry in os.listdir(), it’s not relevant for the problem, but I point it out anyway. (Also, you overwrote the built-in for function)
  • I’ve split up the file using split("\n")
  • I’ve changed the way the files are opened to r+, this doesn’t clear the file unlike w+.

Please note that if you want to use readlines you have to remove the new line for each entry.

import os

with open('list.txt','w+') as file:
    file.write("Foo\n")
    file.write("Bar")
with open('completed.txt','w+') as file:
    file.write("Bar\n")
    file.write("Python")

T = "Albums"
if not os.path.exists(T):
    os.mkdir("Albums")
with open('list.txt','r+') as f:
    linesA = f.read().split("\n")
    print(linesA)
with open('completed.txt','r+') as t:
    linesB = t.read().split("\n")
    print(linesB)
for entry in list(linesA):
    if entry in linesB:
        linesA.remove(entry)
print(linesA)
print(linesB)

Output:

['Foo', 'Bar']
['Bar', 'Python']
['Foo']
['Bar', 'Python']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading