Categories
Python Answers

How to delete a specific line in a file with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *