删除文件A中存在的文件A和B中的行

时间:2017-09-11 18:29:27

标签: python

我遇到了问题。我有一个包含5个链接的blacklist.txt文件

Link1.com
Link2.com
Link3.com
Weirdlink4.com
Fivelink5.com

我还有一个Links.txt,其中包含所有这5个链接和40个以上。 我正在尝试创建一个脚本,可以读取blacklist.txt包含的内容,并从Links.txt中删除这些链接,并删除链接以及blacklist.txt。

with open("Blacklist.txt", "w+") as blacklist:
    with open("Links.txt", "w+") as links:
        blackinfo = blacklist.read()
        linksinfo = links.read()
        for i in blackinfo:
            if i in linksinfo:

此时我对如何从两个文件中删除链接完全感到困惑,因为我持有该值。提前致谢

1 个答案:

答案 0 :(得分:2)

使用列表推导,您可以创建一个新的链接列表,您可以使用以下链接覆盖链接文件:

with open("Blacklist.txt", "r+") as blacklist_file :
    with open("Links.txt", "r+") as links_file :

        bl_links = blacklist_file.read().splitlines()
        blacklist_file.seek(0) #reset file handle's position to start of file for writing

        links = links_file.read().splitlines()
        links_file.seek(0)

        # Only keep blacklist links that did not exist in links
        new_blacklist_links = [link for link in bl_links if link not in links]

        # Only keep links that did not exist in the blacklist
        new_links = [link for link in links if link not in bl_links]

        blacklist_file.write('\n'.join(new_blacklist_links))
        blacklist_file.truncate() #truncate the file to what we have just written

        links_file.write('\n'.join(new_links))
        links_file.truncate()