简体   繁体   中英

Check existing values in text file before appending new values

I'm trying to make a simple cache that stores values I've already generated so I don't append duplicate values into the text file. However, I've been having issues with this, no matter what I seem to try my program keeps appending duplicate values.

Here's my current code, if anyone could point me in the right direction it would be greatly appreciated:

import random

def test():
    cache = open('cache.txt','a+')

    for x in range(10):
        number = random.randint(1,20)
        if number not in cache:
            cache.write(str(number) + '\n')

    print("Finished.")

test()

You will have to keep a track of existing values, before you can add new values. Also, in your current code, you check for the in membership test against a file object, which just won't work.

So instead, read the existing values into a variable first, and then add new values checking if they already exist or not. Also add the newly generated no duplicate random values into existing values.

import random

def test():
    with open('cache.txt','r') as cache:
        existing = [l.rstrip("\n") for l in cache.readlines()]

    with open('cache.txt', 'a+') as cache:
        for x in range(10):
            number = str(random.randint(1,20))
            if number not in existing:
                existing.append(number)
                cache.write(number + '\n')
    print("Finished.")

test()

When you call number not in cache , you are trying to see if number is in an open() object. Instead, read the values from cache first.

cache is a file, not a dictionary or list; you'll need to read in the values from cache before you can do a look up on them.

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