How to delete each and every element inside a specific text file using python?

105 Views Asked by At

I've been programming for nearly 2 years, but I have 5 months python experience. I'm working on an app in tkinter, and I am at the point where I want to delete every singular element inside a .txt file if a button is pressed.

I tried this:

with open("path/to/file", "r+") as file:
    lines = file.readlines()
    file.seek(0)
    for i in lines:
        if i.strip() != "specific_element":
            file.write(str("specific_element"))
    
        i.truncate()

in my other project, but the only problem here is you have to specify the element you'd like to remove, which is in my case, irrelevant. I want all elements to be removed from a txt file.

4

There are 4 best solutions below

4
Satyajeet Sahu On

Try this out:

with open("test.txt", "w") as file:
    file.write("")

Hope it helps!!!

1
TheHungryCub On

If you want to delete all lines from a text file when a button is pressed, you can achieve this by opening the file in “w” mode instead of “r+” mode.

This will open the file for writing and truncate its content. Here’s an example:

with open("path/to/file.txt", "w"):
    # This will open the file in "w" mode, truncating its content and effectively deleting all lines.
    pass

If you want to stick with the “r+” mode and remove all lines individually, you can modify your existing code like this:

with open("path/to/file.txt", "r+") as file:
    # Truncate the content to remove all lines
    file.truncate()

Both of these approaches will delete all lines from the file.

1
Eidnoxon On

Nevermind guys, I found the answer. If you are browsing for the answer as well, here it is:

with open("testFile.txt", "r+") as file:
    file.seek(0)
    file.truncate()
0
SIGHUP On

If you open a file in mode "w", a new, empty, file will be created (subject to any permissions issues). You can then immediately close the file to leave it as empty.

So, as others have said:

with open("foo.txt", "w"):
    pass

...is all you need.

However, the implication of your question is that you want to remove everything from an existing file. The technique above will create a file if it didn't exist.

If you want to empty an existing file then:

import os

os.truncate("foo.txt", 0)

For this to work, the file must already exist. If it doesn't, you'll get a FileNotFoundError exception