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 read the file with open
and readlines
.
Then we open the file again with write permission with open
, loop through each line to find the lines that we want to include and write them back to the file.
For instance, if our file has:
yourfile.txt
foo
bar
nickname_to_delete
baz
Then 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 the file with read permission and read the lines in the file with:
with open("yourfile.txt", "r") as f:
lines = f.readlines()
Then we open the file with write permission, loop through each line and write the lines that we want to include in the file with:
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
Calling f.write
clear the file and only write the line
s we want to include.
Now yourfile.txt
is:
foo
bar
baz
Conclusion
To delete a specific line in a file with Python, we can read the file with open
and readlines
.
Then we open the file again with write permission with open
, loop through each line to find the lines that we want to include and write them back to the file.