【问题标题】:Append api responses to a .txt file without duplicates将 api 响应附加到 .txt 文件而不重复
【发布时间】:2021-05-05 04:52:31
【问题描述】:

我正在尝试将作为 api 调用响应的 ips 写入 .txt 文件。到目前为止,我的代码运行良好,但是当我再次使用我的程序时,我不希望 .txt 文件中已经存在的 ips 被重复。下面的示例代码

with open('ips_I.txt','a +') as myfile:
for ip_src in ip_set:
    if ip_src + '\n' not in myfile.readlines():
            myfile.write(ip_src + '\n')



Output values from api (): 
13.27.124.517 
12.222.230.4
31.157.283.70

after running the program a second time:
13.27.124.517
65.34.22.212.66
13.27.124.517
0.17.345.137

您可以看到 .txt 文件中的值 13.27.124.517 仍在重复。我该如何做到这一点,所以我只将新的 ips 附加到 .txt 文件中,而不添加文件中已经存在的任何重复项?

【问题讨论】:

    标签: python append write


    【解决方案1】:

    您当前读取文件一次,在循环之前,循环内添加的任何其他 ip 将被视为文件中“未包含”并将再次添加,这不是您想要的。 您必须改为在每次迭代中读取文件。请尝试以下操作:

    for ip_src in ip_set:
        with open('ips_I.txt','a +') as myfile:
            if ip_src + '\n' not in myfile.readlines():
                myfile.write(ip_src + '\n')
    

    【讨论】:

    • 感谢您的建议。当我阅读每次迭代时,我仍然会重复。我想我需要放置 if 语句
    • 可能有一些隐藏的空间导致了问题。在检查 ip 是否在文件中时尝试使用 strip()
    猜你喜欢
    • 2012-06-03
    • 2014-01-11
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多