I'm a bit confused about reading my txt file with Python and then appending it a value.
What I'm trying to achieve is to call an API, retrieve the id of the latest object, and check if this id is already in the list of object previously retrieved and posted.
I pre-populated my output file with 5 random id's to see if it works (see the output file firs five rows).
The result of my call was that for each line in my output file it made the check, and then printed five times the id value (from the new API call). Then for the second call, it printed it again 5 times for the first five rows, and for the next five it finally saw id was present since it was the same this time, but printed I found nothing interesting :(
five times too.
What I would like is just have 1 operation read all lines at once, and make the check present/not present, and subsequently write/not write. I'm writing in Py3, but eventually will have to port to Py2.
If you think I'm really doing it wrong overall, let me know, me newb.
Here's the snippet:
with open('Output.txt', 'r') as f:
for line in f.readline():
if idValue in line:
print("I found nothing interesting :(")
else:
send_message_to_slack(string)
print("bingo, message sent!")
# Saving the value retrieved to a text file for the next call
with open("Output.txt", "a") as text_file:
#print("{}".format(idValue), file=text_file)
text_file.write("\n"+idValue)
time.sleep(100)
My log:
Checking id value
Calling API
decode data
retrieving_id
bingo, message sent!
bingo, message sent!
bingo, message sent!
bingo, message sent!
bingo, message sent!
Checking id value
Calling API
decode data
retrieving_id
bingo, message sent!
bingo, message sent!
bingo, message sent!
bingo, message sent!
bingo, message sent!
I found nothing interesting :(
I found nothing interesting :(
I found nothing interesting :(
I found nothing interesting :(
I found nothing interesting :(
And the output file:
5468
64654654
6546
35463
7575337
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
You're really close! To accomplish all of the value checking in one single operation, you should use an intermediate set
to read and store all of the current values, and then check that set
for the existence of your new idValue
:
with open('Output.txt', 'r') as f:
currentValues = set()
for line in f.readline():
currentValues.add(int(line))
if idValue in currentValues:
print("I found nothing interesting :(")
else:
send_message_to_slack(string)
print("bingo, message sent!")
# Saving the value retrieved to a text file for the next call
with open("Output.txt", "a") as text_file:
#print("{}".format(idValue), file=text_file)
text_file.write("\n"+idValue)
time.sleep(100)
Hope this helps!