How to erase the file contents of text file in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Erasing a text file in Python can be a one-line operation, but the correct approach depends on whether the file must already exist, whether other processes may be writing to it, and whether you need a backup first. In simple scripts, truncation is enough. In operational code, you usually want a little more control.
The Fastest Way: Open in Write Mode
Opening a file with mode w truncates it immediately.
After this block runs, app.log exists and is empty. That is perfect when you want "empty file" as the end state and you do not care whether the file already existed.
The side effect is important: if the file does not exist yet, Python creates it. That is convenient in a script and undesirable in workflows that should fail on a wrong path.
Use truncate When the File Must Already Exist
If the file should exist already, open it in r+ mode and truncate explicitly.
This version fails with FileNotFoundError if the path is wrong, which can be a useful safety check. It also makes the intent more explicit: you are clearing an existing file, not creating a new one.
Validate the Path with pathlib
For user-provided or configurable paths, validate before truncating.
This gives you clearer error messages and avoids silently clearing the wrong target because of a bad relative path.
Reset the File with a New Header
Sometimes "erase the contents" really means "clear old content and start a fresh file with a header." Log files, reports, and exported text formats often work this way.
This keeps downstream readers happy if they expect a non-empty first line or metadata marker.
Back Up the File Before Clearing It
If the contents may still be useful for debugging or auditing, make a copy first.
This is common in support scripts where you want a clean file going forward but still need the previous contents for a later investigation.
Concurrency and Locking Matter
If another process is writing to the file, truncating it can create race conditions or partial records. On Unix-like systems, you can lock the file while clearing it.
This does not solve every cross-process coordination problem, but it is better than pretending concurrent writers do not exist. On Windows, use the platform-appropriate file-locking mechanism instead of fcntl.
Atomic Replace for Stricter Safety
If you want to avoid partially updated states, write a replacement file and then swap it into place.
This pattern is especially useful when clearing a file is part of a larger workflow and other readers should either see the old contents or the new empty file, but never an in-between state.
Common Pitfalls
The most common mistake is using mode w when a missing file should have been treated as an error. Another is clearing the wrong file because the code relied on an unexpected working directory. Developers also forget about concurrent writers and assume truncation is safe at any moment. Finally, destructive operations without a backup policy can make troubleshooting much harder when the erased contents were actually still needed.
Summary
- Opening with mode
wis the simplest way to clear a file. - Use
r+withtruncate(0)when the file must already exist. - Validate configurable paths before destructive file operations.
- Create a backup first if the previous contents may matter later.
- Use locking or atomic replacement when reliability matters.
Related reading
- How to escape curly-brackets in f-strings?
- How to establish a connection to DynamoDB using python using boto3
- How to estimate how much memory a Pandas' DataFrame will need?
- How to estimate the progress of a GridSearchCV from verbose output in Scikit-Learn?
- How to execute a file within the Python interpreter?
- How to execute a function asynchronously every 60 seconds in Python?
- How to execute a Python script from the Django shell?
- How to execute multi-line statements within Python's own debugger PDB
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.