Skip to content
Advertisement

How to delete a line from a file?

I have two files (file1 and file2) and want to compare each line of file2 with all lines in file1. And if this condition is satisfied: (ln2[1][0] != ln1[1][0]) and (ln2[1][0] != '-') then I want to remove the current line of file2, i.e. ln2, from the file2. I wrote this code in python, but I have an error.

JavaScript

Also, instead of the last three lines of code, I used: (ln2 = ''), But I had the error: IndexError: string index out of range.

The content of files is like this:

JavaScript

I get the following error:

JavaScript

Advertisement

Answer

Rewriting the code gives us:

JavaScript

I used a different file for the output because I didn’t want to destroy my test data.

But now your resulting file b.txt will contain duplicate lines because of the loop and you output all lines that match the condition while they should be deleted.

JavaScript

According to your question you want to compare each line of the second file with each line of the first file and write the data if not any one of those match. The code needs to reflect this, so we use if not any ....

JavaScript

The result is

JavaScript

A short explanation of arr1 = [line.split() for line in file1]. I used a list comprehension to make the code shorter. And a file is iterable, so I don’t have to use readlines here.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement