Python 检查txt文件中是否有新字符串

Python 检查txt文件中是否有新字符串,python,list,Python,List,我正在尝试制作一个函数来比较两个txt文件。如果它识别出一个文件中的新行,但不在另一个文件中,它会将它们添加到列表中,也会添加到不包含这些新行的文件中。它没有做到这一点。这是我的功能。我做错了什么 newLinks = [] def newer(): with open('cnbcNewLinks.txt', 'w') as newL: for line in open('cnbcCleanedLinks.txt'): if line not in "cnbcNewLi

我正在尝试制作一个函数来比较两个
txt
文件。如果它识别出一个文件中的新行,但不在另一个文件中,它会将它们添加到
列表中,也会添加到不包含这些新行的文件中。它没有做到这一点。这是我的功能。我做错了什么

newLinks = []

def newer():
with open('cnbcNewLinks.txt', 'w') as newL:
    for line in open('cnbcCleanedLinks.txt'):
        if line not in "cnbcNewLinks.txt":
            newLinks.append(line)
            newL.write(line)
        else:
            continue
cleaned = ''.join(newLinks)
print(cleaned)

如果文件不大,则移动列表中的数据, 两个列表在集合中转换并使用“不同”内置函数,两次。
然后在文件中添加差异。

我在python代码中加入了@Alex建议的内容

有关详细信息,请参阅文档

我将文本文件名替换为
a.txt
b.txt
,以便于阅读

# First read the files and compare then using `set`
with open('a.txt', 'r') as newL, open('b.txt', 'r') as cleanL:
    a = set(newL)
    b = set(cleanL)
    add_to_cleanL = list(a - b) # list with line in newL that are not in cleanL
    add_to_newL = list(b - a) # list with line in cleanL that are not in newL

# Then open in append mode to add at the end of the file
with open('a.txt', 'a') as newL, open('b.txt', 'a') as cleanL:
    newL.write(''.join(add_to_newL)) # append the list at the end of newL
    cleanL.write(''.join(add_to_cleanL)) # append the list at the end of cleanL

如果行不在“cnbcNewLinks.txt”中:
只是测试文件名的文本字符串,而不是搜索文件。那么如何搜索新字符串?使用文件句柄
newL
,就像写入文件时一样。这不是一种非常有效的方法,但如果行不在“cnbcNewLinks.txt”中,您可以更改
如果行未处于打开状态(“cnbcNewLinks.txt”).readlines()
并且它可能会工作。更实用的方法是使用双循环。请检查以下问题: