【问题标题】:How to read all lines of text file to return if a value is present and then write this value if not present?如果存在值,如何读取文本文件的所有行以返回,如果不存在则写入该值?
【发布时间】: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


    【解决方案1】:

    你真的很亲密!要在一个操作中完成所有值检查,您应该使用中间 set 来读取和存储所有当前值,然后检查 set 是否存在新的 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)
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 2013-12-24
      • 2020-08-18
      • 2018-04-10
      • 1970-01-01
      相关资源
      最近更新 更多