Be the following list of elements:
listELEMENTS = ['aaa', 'bbb', 'ccc']
and be the following txt file (elements.txt) with lists of elements that should be kept in the list:
elements.txt
aaa
ccc
ddd
the idea is to remove the elements from the listELEMENTS that are not in the elements elements.txt file, so the final result after deletion will be this:
listELEMENTS = ['aaa', 'ccc']
the code I made was this, but it is eliminating all elements. Does anyone know where the error is?
with open("elements.txt") as f:
for line in f:
(key) = line.split()
for i in listELEMENTS :
if i not in key:
listELEMENTS.remove(i)
The problem in your code is that you are checking for each element of listELEMENTS
if it exists in a specific element of the file instead of all file's elements (if i not in key
).
Change your code to:
listELEMENTS = ['aaa', 'bbb', 'ccc']
with open("elements.txt") as f:
file_elements = f.read().splitlines() # read all elements of the file into a list
for i in listELEMENTS:
if i not in file_elements:
# check that i not exists in the full list of elements
listELEMENTS.remove(i)
print(listELEMENTS) # ['aaa', 'ccc']
Or, you can do it in a bit shorter way using list comprehension:
with open("elements.txt") as f:
file_elements = f.read().splitlines()
listELEMENTS = [i for i in listELEMENTS if i in file_elements]
print(listELEMENTS) # ['aaa', 'ccc']