我正在尝试列出要供另一个项目使用的主题,并将这些主题存储在Topics.txt
中。但是,当主题存储在文件中时,我不需要重复的主题。因此,当我将主题保存到我的Topics.txt
文件中时,我也将它们保存到了Duplicates.txt
文件中。我想做的是创建一个条件语句,如果主题在Topics.txt
中,则不会将主题添加到Duplicates.txt
。我的问题是,我不知道如何创建条件语句来检查主题是否在Duplicates.txt
中列出。如果扫描“ music”之类的关键字,发现“ electro-music”包含单词“ music”,则可能会出现问题。
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/