检查txt fi中是否有新字符串

2024-05-16 04:07:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数来比较两个txt文件。如果它识别出一个文件中的新行,而不是另一个文件中的新行,它会将它们添加到list中,也会添加到不包含这些新行的文件中。它没有做到这一点。这是我的职责。我做错什么了?你知道吗

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)

Tags: 文件函数intxtdefwithlineopen
2条回答

我输入了@Alex建议的python代码。你知道吗

参见文档中的^{}。你知道吗

我用a.txtb.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

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

相关问题 更多 >