【发布时间】:2018-11-09 03:31:11
【问题描述】:
我对用 Python 读取我的 txt 文件然后为其附加一个值有点困惑。
我想要实现的是调用一个 API,检索最新对象的 id,并检查此 id 是否已经在之前检索和发布的对象列表中。
我用 5 个随机 id 预先填充了我的输出文件,看看它是否有效(查看输出文件的前五行)。
我调用的结果是,它对输出文件中的每一行进行检查,然后打印 id 值的五倍(来自新的 API 调用)。然后对于第二次调用,它在前五行再次打印了 5 次,在接下来的五行中,它终于看到 id 存在,因为这次是一样的,但也打印了 5 次 I found nothing interesting :(。
我想要的只是一次读取所有行的 1 个操作,并使检查存在/不存在,然后写入/不写入。我正在用 Py3 编写,但最终将不得不移植到 Py2。
如果你认为我真的做错了,请告诉我,我的新手。
这是sn-p:
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)
我的日志:
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 :(
还有输出文件:
5468
64654654
6546
35463
7575337
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
308381357
【问题讨论】:
标签: python-3.x slack readlines