-1

File1.txt contains

text line 1
text line 2
text line 3

File2.txt contains

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

I tried playing around with .readlines statements and if statements inside a for loop with no success

Retardrino
  • 63
  • 6
  • to remove line from file you will have to overwrite it - write all again - so it is easier if you load all to list and work with list and later you write all back to file. – furas Jul 07 '19 at 03:35
  • If you are comfortable using bash/shell, I would check out this answer: https://stackoverflow.com/questions/4366533/how-to-remove-the-lines-which-appear-on-file-b-from-another-file-a – Zaya Jul 07 '19 at 03:36

1 Answers1

0

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360