Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk2 min

How to Clear a File in Python

Use Python’s "w" mode to clear a file when opening it, or seek to the beginning and truncate an already-open writable stream.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To clear an existing file before writing new text, open it in write mode: with open("example.txt", "w", encoding="utf-8") as f:. Opening with "w" truncates the file immediately; it also creates the file if it does not exist and your process has permission to do so.

Choose the right way to clear the file

Situation Use What it does
Clear a file before writing text open(path, "w", encoding="utf-8") Truncates the file as it opens; creates it if missing, subject to filesystem permissions.
Clear a file before writing binary data open(path, "wb") Truncates the file and works with bytes rather than text.
The file is already open and should stay open f.seek(0), then f.truncate(0) Resizes the existing writable stream to zero bytes.
Operate on a path or file descriptor os.truncate(path, 0) or os.ftruncate(fd, 0) Resizes the file through the operating-system interface.

Clear a file by opening it in write mode

Use this when you want to discard the old contents and then write new text. The file is cleared on opening, before any later write happens.

with open("example.txt", "w", encoding="utf-8") as f:
    f.write("New contentsn")

For predictable text encoding, specify one such as UTF-8; otherwise, the default text encoding depends on the platform. Text mode reads and writes str. For binary data, use "wb" and write bytes instead. See the Python documentation for open() modes and the text and binary I/O tutorial.

Use "w+" if you need to read from the newly opened file as well as write to it. Do not choose "r+" expecting it to clear the file: that mode opens an existing file for updating but does not truncate it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Clear an already-open file object

If you need to keep using an open, writable, seekable file object, move to the beginning and truncate there:

with open("example.txt", "r+", encoding="utf-8") as f:
    f.seek(0)
    f.truncate(0)

Calling truncate() without a size uses the current position as the new length. Seeking to zero first is therefore essential; passing 0 explicitly makes the intended zero-byte length clear. Truncation does not change the stream’s current position. The Python I/O reference documents these stream behaviors.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use the operating-system functions when appropriate

For direct path- or descriptor-based truncation, Python provides os.truncate(path, length) and os.ftruncate(fd, length). For example, os.truncate("example.txt", 0) sets the file length to zero. These functions are documented for Unix and Windows in the Python os module reference. The Python FAQ also shows truncation using an open descriptor: file truncation example.

Check the stream and durability requirements

  • A stream must be writable to write or truncate it, and seekable to use seek(). Non-seekable streams cannot use seek(), tell(), or truncate(); check the stream’s capabilities when working with unusual file-like objects.
  • truncate(size) uses bytes, not a count of text characters. With text streams, use supported positions such as the start of the file rather than treating a character index as a byte offset.
  • Truncating a file changes its length; it is not the same as guaranteeing that buffered data has been forced to physical storage. If durability is required, flush a buffered file object before calling os.fsync(f.fileno()). fsync() does not perform the truncation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.