Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting a line from a Python text file

While I was learning how to work with files in Python, I had a question: How can you delete a line from a file that contains a specific word. I wrote the following code:

arr = []
try:
    with open("test.txt") as file:
        arr = file.readlines()
except FileNotFoundError:
    print("File not found!")

word = "five"
try:
    with open("test.txt", "w") as file:
        for row in arr:
            if word not in row:
                file.write(row)
except FileNotFoundError:
    print("File not found!")

But I would like to know if it is possible to do this without writing all the lines in one array, because the file can sometimes be very large and there can be a lack of memory.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can write as you read instead of storing

Consider the following:

try:
    with open("test.txt") as file:
        with open("new_test.txt", "w") as new_file:
            for row in file:
                if word not in row:
                    new_file.write(row)
except FileNotFoundError:
    print("File not found!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading