Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Erase Contents of a File
1
How to Erase Contents of a File

5/5 – (1 vote)

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
Code:
prices.txt
. To ensure no mistakes, you would like to erase the contents of this file before saving the latest data.


[Image: 1f4ac.png] 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
Code:
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
Code:
open()
and
Code:
truncate(0)
.

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

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

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

[Image: 1f4e2.png]Tip: A file object is returned whenever a file is opened in Python. This object allows access to process/manipulate the open file.

Next,
Code:
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,
Code:
fp.close()
is called to close the open file.

If this code is successful, an empty
Code:
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
Code:
open()
,
Code:
seek()
and
Code:
truncate(0)
.

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

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

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

Then,
Code:
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
Code:
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
Code:
with open()
on one-line!

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

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

[Image: 1f4e2.png]Tip: The
Code:
pass
statement is used as a placeholder. When
Code:
pass
executes, nothing happens. This is necessary when code is expected, but no code is required.

If this code is successful, an empty
Code:
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 (
Code:
open()
) and closes said file (
Code:
close()
) using one line of code!

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

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

If this code is successful, an empty
Code:
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?

Code:
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
Code:
prices.txt
(AAPL) and erase the remainder.

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

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

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

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

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

Output

Code:
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.
[Image: 1f469.png][Image: 1f9d4-200d-2642-fe0f.png]
~~~


There are 10 types of people in the world. Those who understand trinary, those who don’t, and those who mistake it for binary.
[Image: 1f469.png][Image: 1f9d4-200d-2642-fe0f.png][Image: 1f471-200d-2640-fe0f.png]
Reply

Users browsing this thread:
1 Guest(s)

Forum Jump: