Sometimes, we want to delete a specific line in a file with Python.
In this article, we’ll look at how to delete a specific line in a file with Python.
How to delete a specific line in a file with Python?
To delete a specific line in a file with Python, we can open the file with open
.
For instance, we write
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
to open yourfile.txt and read the file lines into an iterable with
with open("yourfile.txt", "r") as f:
lines = f.readlines()
And then we loop through the lines and call f.write
to write the new lines into a file with
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
The content in yourfile.txt will be overwritten, so anything other than ‘nickname_to_delete’ will be written into yourfile.txt.
Conclusion
To delete a specific line in a file with Python, we can open the file with open
.