简体   繁体   English

如果它们存在于另一个 txt 文件中,如何从 txt 文件中删除它们

[英]how to remove lines from a txt file if they exist on an another txt file

File1.txt contains File1.txt 包含

text line 1
text line 2
text line 3

File2.txt contains File2.txt 包含

text line 3 
text line 4
text line 5

I wan't to make a file that contains我不想制作一个包含

text line 1
text line 2

so basically If line exists on file2.txt remove it from file1.txt所以基本上如果 file2.txt 上存在该行,则将其从 file1.txt 中删除

I tried playing around with .readlines statements and if statements inside a for loop with no success我尝试在 for 循环中使用 .readlines 语句和 if 语句,但没有成功

Assuming both files are small enough that they can comfortably fit into memory, you could just read both files into a list and then find the difference:假设两个文件都足够小,可以轻松放入内存,您可以将两个文件读入一个列表,然后找出不同之处:

list1 = []
list2 = []

with open("file1.txt") as f:
    list1 = f.readlines()

with open("file2.txt") as f:
    list2 = f.readlines()

list_diff = list(set(list1) - set(list2))

You may then write list_diff to an output file, print it, etc.然后您可以将list_diff写入输出文件,打印它等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM