How To Delete A Line In Python

In this tutorial, we will learn how to delete a line in a text file using Python. The process can be quite useful in various instances, where you may need to manipulate text files by removing specific lines.

We will cover two popular methods of achieving this goal. The first method is to read the contents of a file, remove a line, and then overwrite the original file.

The second method is to open both the input and output files, read a line from the input file, and then write it to the output file except the line you want to delete.

Step 1: Create a sample text file

First, let’s create a sample text file with some lines. Here’s an example (example.txt):

Step 2: Deleting a line by overwriting the original file

To delete a line using this method, follow these steps:

1. Read the contents of the text file and store it in a list, where each line is an element in the list.
2. Remove the line you want to delete from the list.
3. Overwrite the original file with the modified list.

Here’s the code to remove line 3 from example.txt:

Step 3: Deleting a line using input and output files

To delete a line using this method, follow these steps:

1. Open both the input file and a temporary output file.
2. Read a line from the input file.
3. Write it to the output file if the line does not match the line you want to delete.
4. Repeat steps 2 and 3 for all lines in the input file.
5. Close both files.
6. Replace the original file with the temporary output file.

Here’s the code to remove line 3 from example.txt using input and output files:

Full code samples

Conclusion

In this tutorial, we’ve covered two different methods to delete a line in a text file using Python. The first method is by reading the contents of the file, removing the specific sequence, and then overwriting the original file.

The second method is using both input and output files, reading lines from the input file, and writing them to the output file except for the line we want to delete. Both methods can be used depending on your preference and use case.