How to Erase Contents of a File

Problem Formulation and Solution Overview

In this article, you’ll learn how to erase the contents of a file in Python.

To make it more fun, we have the following running scenario:

Let’s say you have a Python script that retrieves the daily stock exchange prices for five (5) Tech Companies and saves it to prices.txt. To ensure no mistakes, you would like to erase the contents of this file before saving the latest data.

πŸ’¬ Question: How would we write code to erase the contents of a file?

We can accomplish this task by one of the following options:


Preparation

To follow along, copy, paste and save the text below to prices.txt. Move this file to the current working directory.

AAPL,138.22
MMSF,255.67
HPE,14.51
DELL,14.51
MNDT,21.89

Method 1: Use open() and truncate()

This method erases the contents of a file without removing the file itself using open() and truncate(0).

fp = open('prices.txt', 'w')
fp.truncate(0)
fp.close()

This code opens prices.txt in write mode (w) and saves the output to fp which creates a file object similar to the output below.

<_io.TextIOWrapper name='prices.txt' mode='w' encoding='cp1252'>

πŸ“’Tip: A file object is returned whenever a file is opened in Python. This object allows access to process/manipulate the open file.

Next, fp.truncate(0) is called. This method resizes the said file to a specified number of bytes. If no argument is passed, the current file position is used.

Finally, fp.close() is called to close the open file.

If this code is successful, an empty prices.txt file now resides in the current working directory.


Method 2: Use open(), seek(0) and truncate(0)

This method opens/re-opens a file and erases the contents without removing the file itself using open(), seek(0) and truncate(0).

fp = open('prices.txt', 'r+')
fp.seek(0) 
fp.truncate() 

This code opens/re-opens the prices.txt file in read/write mode (r+) and saves the output to fp which creates a file object similar to the output above.

Next, fp.seek(0) is called to re-position the file pointer (fp) to a given position in the file. In this case, the position is 0 (the top of the file).

Then, fp.truncate(0) is called. This method resizes the said file to a specified number of bytes. If no argument is passed, the current file position is used.

If this code is successful, an empty prices.txt file now resides in the current working directory.


Method 3: Use with open()

This method erases the contents of a file without deleting the file itself using with open() on one-line!

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

This code calls with open() to open prices.txt for writing (w). Then, the pass statement executes, which does nothing, and the file automatically closes.

πŸ“’Tip: The pass statement isΒ used as a placeholder. When pass executes, nothing happens. This is necessary when code is expected, but not needed.

If this code is successful, an empty prices.txt file now resides in the current working directory.


Method 4: Use open() and close() on one line

Also a good option, this method opens a file for writing (open()) and closes said file (close()) using one line of code!

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

This code uses open() to open prices.txt for writing (w). Since no other code is called, the file contents are erased, and the file closes (close()).

If this code is successful, an empty prices.txt file now resides in the current working directory.


Bonus: Erase File Contents after Specified Location

What happens if you want to erase everything after the first x number of characters in a file and return the same?

import os

fp = os.open('prices.txt', os.O_RDWR|os.O_CREAT)
os.ftruncate(fp, 4)
os.lseek(fp, 0, 0)
str = os.read(fp, 100).decode('utf-8')
print(f"Read String is : {str}")
os.close(fp)

This example could be used for erasing the entire contents of a file. However, let’s retrieve the first four (4) characters from prices.txt (AAPL) and erase the remainder.

First, this code calls in the os library to access the many functions available for interacting with the operating system.

Then, prices.txt is opened in read/write mode, and if the file does not exist, or fails, a new file is created (os.O_RDWR|os.O_CREAT)).

Then, the file is truncated to 4 bytes/characters (os.ftruncate(fp, 4)) and the file pointer (fp) moves to the top of the file (os.lseek(fp, 0, 0)).

Next, the code reads in the first four (4) bytes/characters indicated above and decodes the output (os.read(fp, 100).decode('utf-8')) and saves to str.

The output is sent to the terminal, and the file closes.

Output

Read String is: AAPL

Summary

These four (4) methods of how to erase the contents of a file should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor

There are only 10 kinds of people in this world: those who know binary and those who don’t.
πŸ‘©πŸ§”β€β™‚οΈ
~~~

There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.

πŸ‘©πŸ§”β€β™‚οΈπŸ‘±β€β™€οΈ