How To Delete Lines In Text File Using Python

Deleting certain lines from a text file is a common task that can be accomplished using Python. In this tutorial, we will show you how to do this step by step, using different methods and techniques to manipulate text files.

Method 1: Using a Temporary File

This method involves creating a temporary file and writing lines from the original file to the temporary file, excluding the lines you want to delete. Then, we’ll rename the temporary file to replace the original file.

Step 1: Create a Sample Text File

Let’s create a sample text file named sample_text.txt with the following content:

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.

Step 2: Write Python Code to Delete Specific Lines

In this example, we will delete line 3 from the file.

Output:

After executing the code, the content of the sample_text.txt will be:

This is line 1.
This is line 2.
This is line 4.
This is line 5.

Method 2: Using a List Comprehension

This method involves reading the entire content of the file into memory, modifying it, and then writing the changes back to the file.

Step 1: Write Python Code to Delete Specific Lines

In this example, we will delete lines 2 and 4 from the file.

Output:

After executing the code, the content of the sample_text.txt will be:

This is line 1.
This is line 3.
This is line 5.

Full Code

Method 1:

Method 2:

Conclusion

In this tutorial, we have demonstrated two different methods of deleting specific lines from a text file using Python. The first method created a temporary file, while the second method utilized list comprehension, both methods resulting in a modified text file with the desired lines removed.