Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 831
Vale Avatar asked Mar 18 '23 02:03

Vale


2 Answers

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()
like image 109
Anshul Goyal Avatar answered Mar 19 '23 14:03

Anshul Goyal


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.

like image 24
A.J. Uppal Avatar answered Mar 19 '23 14:03

A.J. Uppal