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.
>Solution :
Does this help:
- I suggest using
not os.path.exists(entry)instead ofnot 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 unlikew+.
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']