How to erase the file contents of text file in Python?

Python

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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+

Solution 2 - Python

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)

Solution 3 - Python

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

Solution 4 - Python

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

with open('filename.txt', 'w'):
    pass

Solution 5 - Python

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.

Solution 6 - Python

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

It Worked for me

Solution 7 - Python

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

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

Solution 8 - Python

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.

Solution 9 - Python

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.

happy coding!

Solution 10 - Python

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.

Solution 11 - Python

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.

Solution 12 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHickView Question on Stackoverflow
Solution 1 - PythonondraView Answer on Stackoverflow
Solution 2 - PythonDouglas LeederView Answer on Stackoverflow
Solution 3 - PythonSnigdha BatraView Answer on Stackoverflow
Solution 4 - PythonCasualCoder3View Answer on Stackoverflow
Solution 5 - PythonwcynView Answer on Stackoverflow
Solution 6 - PythonMohd Tauovir KhanView Answer on Stackoverflow
Solution 7 - PythonAlex KorbanView Answer on Stackoverflow
Solution 8 - PythonNickView Answer on Stackoverflow
Solution 9 - Pythonsujay simhaView Answer on Stackoverflow
Solution 10 - PythonnoskloView Answer on Stackoverflow
Solution 11 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 12 - PythonbsberryView Answer on Stackoverflow