246

I have text file which I want to erase in Python. How do I do that?

1
  • 4
    do open('file.txt', 'w').close() as weird as it looks. Dec 2, 2022 at 6:11

12 Answers 12

478

In Python:

open('file.txt', 'w').close()

Or alternatively, if you have already an opened file:

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
5
  • #include<fstream> and then std::ofstream("file.txt"); about as short as in Python. :) May 4, 2010 at 21:44
  • 15
    the reason this works (in both C++ and python) is because by default when you open a file for writing, it truncates the existing contents. So really it's sorta a side effect, and thus I would prefer the explicit call to truncate() for clarity reasons, even though it is unnecessary.
    – rmeador
    May 4, 2010 at 22:05
  • 11
    if you have opened the file using "r+", use truncate(0) if you have parsed file, which you likely has. Add this to the answer above to have it complete! Apr 20, 2017 at 7:57
  • 7
    use f.seek(0) to move the pointer to the beginning of the file Apr 20, 2017 at 8:05
  • 31
    I was reading as well as writing to file. The answer perfectly truncates the file, but beware if you want to write something to it again don't forget to add f.seek(0) after f.truncate(0), else you will have weird \x00 appended at the start of the file. May 10, 2020 at 8:47
45

Opening a file in "write" mode clears it, you don't specifically have to write to it:

open("filename", "w").close()

(you should close it as the timing of when the file gets closed automatically may be implementation specific)

0
39

Not a complete answer more of an extension to ondra's answer

When using truncate() ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading - open('FILE_NAME','r') it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0) By default truncate() truncates the contents of a file starting from the current cusror position.

A simple example

1
  • this helped me alot to understand how truncate() is working in regard to the cursor position.
    – Frankstar
    Jan 16, 2022 at 13:53
24

As @jamylak suggested, a good alternative that includes the benefits of context managers is:

with open('filename.txt', 'w'):
    pass
1
  • Extra info: "w" (write) mode will automatically truncate/erase the file contents (no need to call file.truncate(0)). For better understanding of the file modes, please refer this flow chart Nov 10, 2023 at 16:27
14

When using with open("myfile.txt", "r+") as my_file:, I get strange zeros in myfile.txt, especially since I am reading the file first. For it to work, I had to first change the pointer of my_file to the beginning of the file with my_file.seek(0). Then I could do my_file.truncate() to clear the file.

1
  • 2
    This should come as no surprised, it was mentioned in this answer 3 years earlier.
    – AMC
    Apr 14, 2020 at 23:19
5

If security is important to you then opening the file for writing and closing it again will not be enough. At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.

Suppose, for example, the file you're erasing contains production passwords and needs to be deleted immediately after the present operation is complete.

Zero-filling the file once you've finished using it helps ensure the sensitive information is destroyed.

On a recent project we used the following code, which works well for small text files. It overwrites the existing contents with lines of zeros.

import os

def destroy_password_file(password_filename):
    with open(password_filename) as password_file:
        text = password_file.read()
    lentext = len(text)
    zero_fill_line_length = 40
    zero_fill = ['0' * zero_fill_line_length
                      for _
                      in range(lentext // zero_fill_line_length + 1)]
    zero_fill = os.linesep.join(zero_fill)
    with open(password_filename, 'w') as password_file:
        password_file.write(zero_fill)

Note that zero-filling will not guarantee your security. If you're really concerned, you'd be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the 'empty' space on your drive.

5

Writing and Reading file content

def writeTempFile(text = None):
    filePath = "/temp/file1.txt"
    if not text:                      # If not provided return file content
        f = open(filePath, "r")
        slug = f.read()
        return slug
    else:
        f = open(filePath, "a") # Create a blank file
        f.seek(0)  # sets  point at the beginning of the file
        f.truncate()  # Clear previous content
        f.write(text) # Write file
        f.close() # Close file
        return text
3

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();
3
  • 1
    There's no need for the close() call. The destructor will close the file. So you just need to create a temporary: ofstream("test.txt"); May 4, 2010 at 21:40
  • This question has changed since this answer. Maybe delete the question given the new direction of the question?
    – Seanny123
    May 1, 2019 at 18:39
  • This is not python. Jun 19, 2022 at 18:06
3

You can also use this (based on a few of the above answers):

file = open('filename.txt', 'w')
file.close()

of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.

0

You cannot "erase" from a file in-place unless you need to erase the end. Either be content with an overwrite of an "empty" value, or read the parts of the file you care about and write it to another file.

3
  • ok how to overwrite it without giving garbage value? i mean suppose a string length of 9 is there and i am overwriting it with string length of 6 . that would mean 3 garbage values rt?
    – Hick
    May 4, 2010 at 21:24
  • Correct. Plus you would have to have some way of identifying to any reader the fact that those 3 characters are garbage. May 4, 2010 at 21:28
  • the fact is my code is spanned between python and c++ . so if a file read is done in C++ and file write in python .. both the time the file has to be erased..
    – Hick
    May 4, 2010 at 21:32
0

Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file's still there. I think the remove() function in the c stdio.h is what you're looking for there. Not sure about Python.

1
  • 2
    BTW, both remove() and unlink() will decrease the reference count on a regular file, not actually erase it. The file will be erased once the reference count drops to zero. For example, if your process has the file open and you call unlink() or remove() on it, it won't be deleted until the file is close()d (i.e. ref count drops to zero - also assumes no other processes have the file open). This behavior is useful, for example, to ensure temporary files are not left around after abnormal process termination (e.g. open(), unlink(), perform file IO, CRASH, close() NOT called). May 4, 2010 at 21:54
0

Since text files are sequential, you can't directly erase data on them. Your options are:

  • The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
  • You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
  • Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.

Look at the seek/truncate function/method to implement any of the ideas above. Both Python and C have those functions.

2
  • i just want to erase the whole file from the begining
    – Hick
    May 4, 2010 at 21:23
  • 2
    Then just remove the file. Use os.remove or os.unlink in python, or unlink in C. Another option is to just reopen the file for writing or use truncate.
    – nosklo
    May 4, 2010 at 21:30

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.