【发布时间】: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 文件中,而不添加文件中已经存在的任何重复项?
【问题讨论】: