gpt4 book ai didi

python - 检查文件中的数据是否重复 (Python)

转载 作者:太空宇宙 更新时间:2023-11-03 16:18:44 25 4
gpt4 key购买 nike

我正在尝试制作一个主题列表以供另一个项目使用,并将这些主题存储在 Topics.txt 中。但是,当主题存储在文件中时,我不想要重复的主题。因此,当我将主题保存到 Topics.txt 文件时,我还将它们保存到 Duplicates.txt 文件中。我想要做的是创建一个条件语句,如果主题位于 Duplicates.txt 中,则不会将主题添加到 Topics.txt 中。我的问题是,我不知道如何创建一个条件语句来检查该主题是否在 Duplicates.txt 中列出。如果您扫描“音乐”等关键字,发现“电子音乐”包含“音乐”一词,则可能会出现问题。

Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
Readfile = open(Readfilename, "r")
Readdata = Readfile.read()
Readfile.close()
if Topic not in Duplicates:
Filename = "Topics.txt"
File = open(Filename, "a")
File.append(Topic)
File.close()
Duplicate = Topic + "\n"
Readfile = open(Readfilename, "a")
Readfile.append(Topic)
Readfile.close()

最佳答案

您可以逐行读取文件,这将导致像这样的解决方案

Entry = input("Enter topic: ")
Topic = Entry + "\n"
Readfilename = "Duplicates.txt"
found=False
with open(Readfilename, "r") as Readfile:
for line in Readfile:
if Topic==line:
found=True
break # no need to read more of the file

if not found:
Filename = "Topics.txt"
with open(Filename, "a") as File:
File.write(Topic)

with open(Readfilename, "a") as Readfile:
Readfile.write(Topic)

关于python - 检查文件中的数据是否重复 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com