简体   繁体   中英

Remove items from list if they are already in txt file

Im trying to run this code but im having a problem, it's not working as i need.
What i need is to check if a code from the items list is already saved in the file.txt if it's already there i need to delete that item from the list.
And then save the items list as string in a new file.txt

items = [['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]

for i, item in enumerate(items):
    with open('file.txt') as f:
        if item[0] in f.read():
            items.pop(items.index(item))

with open('file.txt', 'w') as f:
    f.write(str(items))

print(items)

When i first run this code file.txt will be empty so the output should be:

[['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]

Then if i run the same code again the output should be a empty items list (because they are all saved in the file before and deleted from the list).

But when i run this the first output is correct, i get the list from items, if i run it again then im getting this as output:

[['e6056', '2020-06-10'], ['100080020', '2020-06-10'], ['KW13012', '2020-06-10']]

Why this codes wasn't deleted from the list?


I figured out that the items deleted from the list are the even numbers of the list. But i can't understand why:/

If you want to save your list as a list, you can use the json module to serialize it. This will let you load and save the list easily.

Then you can load the file and process a data structure that will let you test easily for inclusion. A set is the obvious choice. Once you have that you can filter your list based on whether items are in this set and then dump the list back to the file.

This assumes a file already exists (even if it's empty):

items = [['e5860', '2020-06-10'], ['e6056', '2020-06-10'], ['e6008', '2020-06-10'], ['100080020', '2020-06-10'], ['e6463', '2020-06-10'], ['KW13012', '2020-06-10'], ['e3589', '2020-06-10']]


with open(filePath, 'r') as f:
    data = f.read()
    if data:
        file_items = json.loads(data)

        # create a set of just the first items in the sub lists:
        seen = set(item[0] for item in file_items)

    else: # empty file, make an empty set
        seen = set()

filtered = [item for item in items if item[0] not in seen]

print(filtered)


with open(filePath, 'w') as f:
    json.dump(filtered,f)

This will alternate between an empty file and a file that contains json of all your items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM