Python3如何检查项目是否已在txt文件中

时间:2019-11-16 14:22:47

标签: python

下面的代码将一个列表作为输入,并将每个项目附加到TXT文件中。 尽管如此,我仍无法弄清楚如何检查列表中的某个项目是否已存在于该TXT文件中,因此我可以忽略该列表,而不必再次添加它。

with open(path2, 'a') as f:
    for item in mylist:
        f.write(item+'\n')

2 个答案:

答案 0 :(得分:0)

您可以在写入前先进行读取,以检查文件是否已包含该文件。不要忘记以seek

开始重新设置读取
my_list =['HI',
         'This',
         'IS',
         'A',
         'TEST',
         'HI',
         'CONTINUE',
         'IS']
with open('test.txt', 'w+') as f:
    for item in my_list:
        f.seek(0)
        if item not in f.read():
            f.write("%s\n" % item)

这会将以下内容写入文件:

HI
This
IS
A
TEST
CONTINUE

答案 1 :(得分:0)

正如基思(Keith)回答您的问题时所说的那样,此处的Set对象将是一种有用的方法。

x = set()

with open("filename.txt", 'r') as fil:
    for line in fil.readlines():
        x.add(line.strip()) # Remove newline character and other whitespace chars from the end

for item in yourlist:
    x.add(str(item))

with open("filename.txt", 'w') as fil: # opening with 'w' will overwrite the file
    for set_item in x:
        fil.write(set_item + '\n')

当然,这将重写整个文件,这可能需要花费一些时间,并且存在很多行,并且还有不同的解决方案,这只是其中之一。

另一种解决方案是读取文件的所有内容并将它们保存到第二个列表中,然后将输入列表与文件输出列表进行比较,并写入文件中没有的每个列表项

fil_list = []
with open("filename.txt", 'r') as fil:
    for line in fil.readlines():
        fil_list.append(line.strip())

with open("filename.txt", 'a') as fil:
    for item in your_list:
        if not (item in fil_list):
            fil.write(str(item) + '\n')

自然地,如果您的列表项已经是字符串,并且如果它们已经包含换行符,则省略'\ n'和str()函数。你明白了。

相关问题