簡體   English   中英

比較文件並刪除一些特定行 python

[英]Compare files and delete some specific lines python

我有 2 個文件。 他們都有很多一行一行的名字。 第一個文件有 184 行,第二個文件有 755 行。 我想將第一個文件中的行與第二個文件中的行以及相等的行進行比較,我從第一個文件中刪除它們。 因此,讓第一個文件只包含不相等或不存在於第二個文件中的行。 我一直在這里嘗試,但是我正在做一些我還沒有發現的錯誤。

這是一個示例,兩個文件都具有這種格式的名稱,逐行:

Sociedade Ação
Águia de Marabá
Amazonas FC
América (RN)
Aparecidense
Araguacema
ASSU
Atibaia
Atlético Gloriense
...

這個怎么樣:

with open('file1.txt', 'r', encoding='utf-8') as f1:
    names1 = f1.readlines()

with open('file2.txt', 'r', encoding='utf-8') as f2:
    names2 = f2.readlines()

with open('file1.txt', 'w', encoding='utf-8') as f3:
    for name in names1:
        if name in names2:
            continue
        f3.write(name)

文件1.txt

Sociedade Ação
Águia de Marabá
Amazonas FC
América (RN)
Aparecidense
Araguacema
ASSU
Atibaia
Atlético Gloriense

文件2.txt

Sociedade Ação
Águia de Marabá
Amazonas FC
dfgh
hdfgh
hdfgh
hdfghd
sdfs
sdfs
sdfs
sdfs
sdfs
sdfgsdfgsfgsd
sdfgsdfgsfgsd
sdfgsdfgsfgsd
sdfgsdfgsfgsd

修改后的file1.txt

América (RN)
Aparecidense
Araguacema
ASSU
Atibaia
Atlético Gloriense

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM