06-14-2022, 09:54 AM
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. 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. 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 and .
This code opens in write mode () and saves the output to which creates a file object similar to the output below.
Tip: A file object is returned whenever a file is opened in Python. This object allows access to process/manipulate the open file.
Next, 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, is called to close the open file.
If this code is successful, an empty 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, and .
This code opens/re-opens the file in read/write mode () and saves the output to which creates a file object similar to the output above.
Next, is called to re-position the file pointer () to a given position in the file. In this case, the position is (the top of the file).
Then, 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 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 on one-line!
This code calls to open for writing (). Then, the statement executes, which does nothing, and the file automatically closes.
Tip: The statement is used as a placeholder. When executes, nothing happens. This is necessary when code is expected, but no code is required.
If this code is successful, an empty 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 () and closes said file () using one line of code!
This code uses to open for writing (). Since no other code is called, the file contents are erased, and the file closes ().
If this code is successful, an empty 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?
This example could be used for erasing the entire contents of a file. However, let’s retrieve the first four (4) characters from (AAPL) and erase the remainder.
First, this code calls in the library to access the many functions available for interacting with the operating system.
Then, is opened in read/write mode, and if the file does not exist, or fails, a new file is created ().
Then, the file is truncated to 4 bytes/characters () and the file pointer () moves to the top of the file ().
Next, the code reads in the first four (4) bytes/characters indicated above and decodes the output () and saves to .
The output is sent to the terminal, and the file closes.
Output
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]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png)
![[Image: 1f9d4-200d-2642-fe0f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/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]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png)
![[Image: 1f9d4-200d-2642-fe0f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d4-200d-2642-fe0f.png)
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
Question: How would we write code to erase the contents of a file?We can accomplish this task by one of the following options:
- Method 1: Use andCode:
open()Code:truncate(0)
- Method 2: Use ,Code:
open()andCode:seek(0)Code:truncate(0)
- Method 3: Use Code:
with open()
- Method 4: Use andCode:
open()on one lineCode:close()
- Bonus: Extract Characters and Erase Remainder
Preparation
To follow along, copy, paste and save the text below to
Code:
prices.txtAAPL,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()Code:
truncate(0)Code:
fp = open('prices.txt', 'w')
fp.truncate(0)
fp.close()This code opens
Code:
prices.txtCode:
wCode:
fpCode:
<_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,
Code:
fp.truncate(0)Finally,
Code:
fp.close()If this code is successful, an empty
Code:
prices.txtMethod 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()Code:
truncate(0)Code:
fp = open('prices.txt', 'r+')
fp.seek(0) fp.truncate()This code opens/re-opens the
Code:
prices.txtCode:
r+Code:
fpNext,
Code:
fp.seek(0)Code:
fpThen,
Code:
fp.truncate(0)If this code is successful, an empty
Code:
prices.txtMethod 3: Use with open()
This method erases the contents of a file without deleting the file itself using
Code:
with open()Code:
with open('prices.txt', 'w'): passThis code calls
Code:
with open()Code:
prices.txtCode:
wCode:
pass
Tip: The Code:
passCode:
passIf this code is successful, an empty
Code:
prices.txtMethod 4: Use open() and close() on one line
Also a good option, this method opens a file for writing (
Code:
open()Code:
close()Code:
open('prices.txt', 'w').close()This code uses
Code:
open()Code:
prices.txtCode:
wCode:
close()If this code is successful, an empty
Code:
prices.txtBonus: 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.txtFirst, this code calls in the
Code:
osThen,
Code:
prices.txtCode:
os.O_RDWR|os.O_CREAT)Then, the file is truncated to 4 bytes/characters (
Code:
os.ftruncate(fp, 4)Code:
fpCode:
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')Code:
strThe output is sent to the terminal, and the file closes.
Output
Code:
Read String is: AAPLSummary
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]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png)
![[Image: 1f9d4-200d-2642-fe0f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/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]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f469.png)
![[Image: 1f9d4-200d-2642-fe0f.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d4-200d-2642-fe0f.png)

