Hellosiroverthere
Hellosiroverthere

Reputation: 315

declare a value is not there after x amount of tries

I am trying to create a script where it checks a text file and checks if values 'names' contains names or not after x amount of tries.

For now I have managed to create a script that opens the text file which contains a json format. I have also added a counter that checks if the names is empty after x amount of tries. It will declare it as no names. and if there is a value it will print out new names.

    text file:


{
    "name": "All new names",
    "url": "www.randomsite.com",
    "names": []
}



with open('./test.txt') as f:
        old_product_values = json.load(f)

    count = 0
    while True:



        with open('./test.txt') as f:
            new_product_values = json.load(f)

        print(new_product_values)

        if count == 10:
            no_names = True
            print('Declare value as No names')

        if not new_product_values['names']:
            count += 1
            time.sleep(1)

        else:
            print("NEW NAMES!")
            print(new_product_values['names'])

What I expect for following results is, where I detect no names, I don't immediately declare it as No names. I want to add one to a counter each time but if that counter hits x amount of time etc. 10 times. Then I declare it as there is no names in the text file. But each time that it detects new names added, it should print out all the names only ONCE and then continue to see if the names is empty after x times. I want to reset the counter everytime it finds new names. only prolonged periods of no names will actually count as no new names.

Upvotes: 0

Views: 50

Answers (1)

keineahnung2345
keineahnung2345

Reputation: 2701

import json
import time

count = 0
last_names = []

while True:
    with open('./test.txt', 'r') as f:
        new_product_values = json.load(f)

    if not new_product_values['names']:
        count += 1
        time.sleep(1)
    elif new_product_values['names']!=last_names:
        print("NEW NAMES!")
        print(new_product_values['names'])
        last_names = new_product_values['names']

    if count == 10:
        no_names = True
        count = 0
        print('Declare value as No names')

This should satisfy your requirements:

  1. Detect no names for 10 times and then declare.

  2. When new names detected, only output them once.

  3. Reset the counter every time it finds new names.

Upvotes: 1

Related Questions