Python
file handling
text files
file operations
programming tutorial

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.

Browse interview questions

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.

python
1path = "app.log"
2
3with open(path, "w", encoding="utf-8"):
4    pass

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.

python
with open("app.log", "r+", encoding="utf-8") as file_handle:
    file_handle.seek(0)
    file_handle.truncate(0)

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.

python
1from pathlib import Path
2
3
4def clear_text_file(path_str: str) -> None:
5    path = Path(path_str)
6    if not path.exists() or not path.is_file():
7        raise FileNotFoundError(path)
8
9    path.write_text("", encoding="utf-8")
10
11
12clear_text_file("app.log")

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.

python
1from datetime import datetime, timezone
2
3with open("report.txt", "w", encoding="utf-8") as file_handle:
4    timestamp = datetime.now(timezone.utc).isoformat()
5    file_handle.write(f"Report reset at {timestamp}\n")

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.

python
1from datetime import datetime
2from pathlib import Path
3import shutil
4
5source = Path("app.log")
6
7if source.exists():
8    stamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
9    backup = source.with_name(f"app-{stamp}.log.bak")
10    shutil.copy2(source, backup)
11
12with open(source, "w", encoding="utf-8"):
13    pass

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.

python
1import fcntl
2
3with open("app.log", "r+", encoding="utf-8") as file_handle:
4    fcntl.flock(file_handle, fcntl.LOCK_EX)
5    file_handle.seek(0)
6    file_handle.truncate(0)
7    fcntl.flock(file_handle, fcntl.LOCK_UN)

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.

python
1from pathlib import Path
2import os
3
4path = Path("app.log")
5temp_path = path.with_suffix(".tmp")
6
7temp_path.write_text("", encoding="utf-8")
8os.replace(temp_path, path)

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 w is the simplest way to clear a file.
  • Use r+ with truncate(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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.