Understanding how to manipulate files is crucial when we are dealing with data. In Python, we have the built-in capability to read, write, and delete data from a file. In this tutorial, we will discuss how to delete data from a file in Python.
Start off by making sure you have a file to work with. For this tutorial, let’s assume we have a text file named “example.txt” that contains the following lines of text:
This is line 1 This is line 2 This is line 3
Step 1: Opening the File
The first thing that we need to do is open the file. We can do that using the built-in open() function in Python. The open() function returns a file object, which is then used for other operations such as read, write, etc.
1 |
file = open('example.txt', 'r') |
Step 2: Reading the File
The next step is to read the file. We accomplish this using the readlines() function. This function reads all the lines of a file and returns them as a list where each line is an item in the list.
1 |
lines = file.readlines() |
Step 3: Modifying the Data
After reading the file, we can remove the data that we don’t want. For example, if we want to remove the second line (“This is line 2”), we can do so by removing the second element from the list (keep in mind that list indexing in Python starts at 0).
1 |
del lines[1] |
Step 4: Writing the Modified Data Back to the File
After making the modifications, we need to write the modified data back to the file. Note that you need to open the file in write mode (‘w’) to do this.
1 2 3 4 |
file = open('example.txt', 'w') for line in lines: file.write(line) file.close() |
Full Code:
Here is the full Python code that illustrates all the steps we have discussed:
1 2 3 4 5 6 7 8 9 10 |
file = open('example.txt', 'r') lines = file.readlines() file.close() del lines[1] file = open('example.txt', 'w') for line in lines: file.write(line) file.close() |
This is line 1 This is line 3
Conclusion:
In this tutorial, we have learned how to delete a specific line of data from a file in Python. We achieved this by opening and reading the file, storing the lines in a list, modifying the list, and then writing the modified list back to the file.
This tutorial only scratches the surface of file handling in Python. There are many other operations we can perform on files such as renaming and deleting files, creating new files, etc.
Be sure to check out the Python documentation to further explore file handling.