Explain it simply
Explain it simply
Writing to a file is like writing on a whiteboard. "w" wipes the board first and then writes, so everything that was there is gone. "a" writes below what is already on the board. "x" is the careful option: "I will only write on an empty board; if someone has already written here, I leave it alone."
One thing to watch: unlike print(), write() never adds a newline for you. If you do not put \n at the end yourself, all your lines end up glued together on a single line.
Problem → Why → Solution
The problem: ten orders written, one left
The script below is meant to write each order to orders.txt. When you open the file afterwards, only the last order is there, and no error ever appeared. Yesterday's report is gone too. And if the laptop battery dies while a settings file is being saved, that file can be left half-written or empty.
orders = ["#101 tea", "#102 coffee", "#103 juice"]
for order in orders:
with open("orders.txt", "w", encoding="utf-8") as f: # reopened every pass
f.write(order) # and no newline
# orders.txt now contains only: #103 juiceWhy does this happen?
Mode "w" truncates the file the moment it opens. Because the open() sits inside the loop, every iteration erases the previous order and writes a new one. The fix is to open the file once, outside the loop, or to use mode "a". Writing is also not instant: data moves from a buffer to the disk in steps, so an interruption halfway can leave a partial file.
Core concept: the mode decides what happens to existing data
The three writing modes differ only in what they do when the file already exists. When it does not exist, all three create it, as long as the parent folder exists; if the folder is missing you get FileNotFoundError.
| Mode | If the file already exists | Good for |
|---|---|---|
| "w" | Empties it and writes from the start | Regenerating a report from scratch |
| "a" | Keeps the content and writes at the end | Logs and audit trails |
| "x" | Raises FileExistsError and changes nothing | Files that must never be overwritten |
In text mode, f.write(text) accepts only a str and returns the number of characters it wrote. To write a number, convert it with str() or an f-string first, or you get a TypeError. print(value, file=f) does the conversion and adds the newline, which makes it handy for writing line by line. f.writelines(list_of_strings) writes the strings back to back and, despite its name, adds no newlines; "\n".join() plus write() is usually clearer.
When write() returns, the data is not necessarily on the disk yet. Python collects it in a buffer and hands it to the operating system when the buffer fills, when you call f.flush(), or when the file closes. The operating system may cache it a little longer, and os.fsync(f.fileno()) asks it to commit the data to disk. So a crash can leave the old file, the new file, or a mix of both. For important files, the atomic write pattern in the deeper section removes that third outcome.
Text mode translates newlines as well. On Windows each \n you write becomes \r\n on disk, while Linux and macOS keep it as \n. To control line endings exactly, pass a newline argument such as open(path, "w", encoding="utf-8", newline="\n"). When writing with csv.writer, pass newline="" because the csv module writes its own line endings. Binary data such as an image is written in mode "wb", and write() then takes bytes instead of a str.
- Ask: does the file exist already?
- Wipe it and start over: "w"
- Keep it and extend it: "a"
- Refuse to touch it: "x"
Choosing a mode is choosing the fate of existing data, and "w" cannot be undone.
General pattern
with open(path, "w", encoding="utf-8") as f: # or "a" / "x"
f.write("text\n") # you add the newline
print(value, file=f) # converts + adds newline
f.write("\n".join(lines) + "\n") # many lines at once
path.write_text(text, encoding="utf-8") # small file, mode "w"Pick the mode for your purpose and always pass an encoding. With write() you add \n yourself; print(file=f) adds it for you. path.write_text() opens in mode "w", writes and closes in one call.
Example: w, a and x in a row
This example uses all three modes in turn on log.txt in a temporary folder: "w" creates it, "a" adds to it, and "x" tries to overwrite it and is refused. Finally it reads the file back to check what survived.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
log = Path(tmp) / "log.txt"
with open(log, "w", encoding="utf-8") as f: # create, or empty an old file
count = f.write("Log started.\n")
print(f"write() returned {count}")
with open(log, "a", encoding="utf-8") as f: # keep content, add at the end
f.write("New entry added.\n")
print("Printed into the file", file=f)
try:
with open(log, "x", encoding="utf-8") as f: # "x": create only if missing
f.write("never written")
except FileExistsError:
print("x mode refused: log.txt already exists")
print(log.read_text(encoding="utf-8"), end="")Code breakdown
- Line 8
count = f.write("Log started.\n")"Log started." is 12 characters and the \n makes 13, which is what write() returns. In text mode this number counts characters, not bytes.
- Lines 11-13
print("Printed into the file", file=f)Mode "a" keeps the first line and writes below it. print(..., file=f) sends its output to the file instead of the screen and adds the newline for you.
- Lines 15-19
except FileExistsError:Because log.txt exists, open(log, "x") raises FileExistsError before opening anything. "never written" is never written and the file's content is untouched.
- Line 21
print(log.read_text(encoding="utf-8"), end="")Reading the file back shows all three lines. The content already ends in \n, so end="" stops print() from adding another one.
write() returned 13
x mode refused: log.txt already exists
Log started.
New entry added.
Printed into the fileAtomic writes: never leave a half-written file
Writing a settings file or a save game directly with "w" means a crash after the truncate but before the write finishes destroys both the old data and the new. The safe pattern is:
1. Write to a temp file
Write the full content to a temp file in the same folder as the target, so both live on the same filesystem.
2. Flush and fsync
f.flush() and os.fsync() make sure the bytes really reach the disk.
3. os.replace()
os.replace(temp, target) swaps the target in one step. The Python documentation notes that on POSIX systems a successful rename is atomic, so readers see either the old file or the new one.
import json
import os
import tempfile
from pathlib import Path
def save_json_atomic(path: Path, data: dict) -> None:
tmp_path = path.with_name(path.name + ".tmp")
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno()) # ask the OS to commit the bytes to disk
os.replace(tmp_path, path) # swap the finished file into place
with tempfile.TemporaryDirectory() as tmp:
settings = Path(tmp) / "settings.json"
save_json_atomic(settings, {"theme": "dark", "font_size": 14})
save_json_atomic(settings, {"theme": "light", "font_size": 16})
print(json.loads(settings.read_text(encoding="utf-8")))In real projects
Where this shows up in real projects
Application logs, audit trails and data exports rely on mode "a": each event appends one line and earlier records are never rewritten. Nightly report generators use "w" to rebuild their output from scratch, while code that names files after something unique, such as an invoice number, uses "x" so an existing file can never be overwritten by accident.
Text editors, package managers and many database tools use the atomic write pattern. If a desktop app crashes while the user is changing settings.json, the old file survives intact. Web servers likewise save an uploaded file under a temporary name and rename it only after it passes validation, so no other process ever reads a file that is still being written.
Common mistakes
Common mistakes
1. Opening with "w" inside a loop
Reopening with "w" on every iteration, as the problem section did, erases the previous content each time. Move the with block outside the loop and put the loop inside the block.
2. Expecting writelines() to add newlines
f.writelines(["a", "b"]) writes "ab", not two lines. Make sure each string ends in \n, or use f.write("\n".join(items) + "\n").
3. Passing a non-string to write()
f.write(42) raises TypeError: "write() argument must be str, not int". Use f.write(f"{42}\n") or print(42, file=f). For dicts and lists, use json.dump() rather than str(), so the file can be read back reliably.
4. Writing into a folder that does not exist
"w" creates the file but not the folders above it, so writing reports/2026/jan.txt raises FileNotFoundError when reports/2026 is missing. Call path.parent.mkdir(parents=True, exist_ok=True) before opening.
Best practices
Best practices
- Each time you type "w", ask yourself whether losing the old file is acceptable.
- Open the file once before a loop and call write() inside it; it is faster as well.
- Write structured data with the json or csv module, not with str().
- Save important files with an atomic write, then read them back to confirm.
Mini challenge
Mini challenge: build an audit log
Write log_event(), which appends one event as a line to audit.log. The "# audit log" header is written only when the file is new; later calls must not repeat it.
- Write the header with mode "x" and catch FileExistsError
- Append events with mode "a"; never use "w"
- Every event goes on its own line
- Test it in a temporary directory and print the line count
import tempfile
from pathlib import Path
def log_event(path: Path, event: str) -> None:
"""Append one event; write the header only when the file is new."""
# TODO: try to open the file in "x" mode and write "# audit log" plus a newline
# TODO: if it already exists, skip the header
# TODO: open in "a" mode and write the event on its own line
...
with tempfile.TemporaryDirectory() as tmp:
audit = Path(tmp) / "audit.log"
# TODO: log three events, then one more as if from a later run
# TODO: print the file's content and the number of linesExpected: The program prints: # audit log login aye export report logout aye login mya lines: 5
Show hint
Use try: with open(path, "x", ...) as f: ... except FileExistsError: pass. print(event, file=f) adds the newline for you.
Show solution
import tempfile
from pathlib import Path
def log_event(path: Path, event: str) -> None:
"""Append an event line, creating the file with a header the first time."""
try:
with open(path, "x", encoding="utf-8") as f:
f.write("# audit log\n")
except FileExistsError:
pass # header is already there
with open(path, "a", encoding="utf-8") as f:
print(event, file=f)
with tempfile.TemporaryDirectory() as tmp:
audit = Path(tmp) / "audit.log"
for event in ["login aye", "export report", "logout aye"]:
log_event(audit, event)
log_event(audit, "login mya") # a later run: no second header
content = audit.read_text(encoding="utf-8")
print(content, end="")
print("lines:", len(content.splitlines()))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- "w" truncates on open, "a" appends, "x" refuses an existing file.
- write() takes only a str and adds no newline; print(file=f) adds one.
- writelines() adds no newlines either; prefer "\n".join() with write().
- Save important files atomically: temp file, flush and fsync, then os.replace().
Python Documentation — Reading and Writing Files — Python Software Foundation