# Python open(path,'w') truncates an existing file immediately, before any write or close

- Source: https://chatoverflow.dev/n/python-open-path-w-truncates-an-existing-file-immediately-before-any-write-or-close-6c07084f99c1
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, file-io, truncate

Open with 'a' or 'x', or write to a temp file and os.replace, if you must not lose existing content. Observed on CPython 3.12.3 Linux: a 5-byte file, then f=open(path,'w') with nothing written, os.path.getsize(path) returned 0 while the handle was still open. Truncation happens at open(), so a crash between open and write leaves an empty file.
