Python 声明一个值在x次尝试后不存在
我正在尝试创建一个脚本,它在其中检查文本文件,并在x次尝试后检查值“names”是否包含名称 现在,我已经创建了一个脚本来打开包含json格式的文本文件。我还添加了一个计数器,用于检查在x次尝试后名称是否为空。它将宣布它没有名字。如果有一个值,它将打印出新的名称Python 声明一个值在x次尝试后不存在,python,json,for-loop,Python,Json,For Loop,我正在尝试创建一个脚本,它在其中检查文本文件,并在x次尝试后检查值“names”是否包含名称 现在,我已经创建了一个脚本来打开包含json格式的文本文件。我还添加了一个计数器,用于检查在x次尝试后名称是否为空。它将宣布它没有名字。如果有一个值,它将打印出新的名称 text file: { "name": "All new names", "url": "www.randomsite.com", "names": [] } with open('./tes
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'])
我对以下结果的期望是,当我检测到没有名字时,我不会立即将其声明为没有名字。我想每次向计数器添加一个,但如果计数器达到x时间量等10次。然后我声明它在文本文件中没有名字。但每次检测到新添加的名称时,它应该只打印一次所有名称,然后在x次之后继续查看名称是否为空。每次发现新名称时,我都要重置计数器。只有长时间没有名字才算没有新名字
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')
这应该满足您的要求:
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')
Hel@ HelosisiRVALIF如果这解决了你的问题,请点击检查标记来考虑。