1

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.

3
  • Do you mean you want to replace the file with an empty file? Commented Jan 20, 2024 at 9:48
  • Have a look at: How to delete specific strings from a file? Commented Jan 20, 2024 at 9:55
  • Apart from moving the truncate outside of the for loop (for efficiency) I don't see any problem Commented Jan 20, 2024 at 10:10

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this out:

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

Hope it helps!!!

4 Comments

Chatgpt wrote the same thing but I never thought it would actually work... Lemme try
Why the call to file.write() ?
Calling file.write("") to write empty string into the file. Which is to delete everything inside it.
@SatyajeetSahu The write call is unnecessary and irrelevant
0

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()

1 Comment

Can you explain why you had the comparisons in your original question? It looked as though you wanted to retain some content

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.