Open the file in append mode (mode="a", encoding="utf-8") inside a with statement and either call print(line, file=f) (which appends a newline automatically) or f.write(f"{line}\n")—checking whether an existing non-empty file already ends with \n if external writers might have left a trailing partial line without a newline.
Basic Example
from pathlib import Path
log_path = Path("events.log")
# 1. Recommended (cleanest — print() appends "\n" automatically):
with open(log_path, mode="a", encoding="utf-8") as f:
print("2026-11-29 16:55:00 - Service started", file=f)
print("2026-11-29 16:55:05 - Worker ready", file=f)
# 2. Recommended (explicit f.write() with trailing "\n"):
with open(log_path, mode="a", encoding="utf-8") as f:
f.write("2026-11-29 16:55:10 - Task completed\n")
# 3. Safe helper when an existing file might NOT end with a trailing newline:
def append_line(path: str | Path, text: str) -> None:
p = Path(path)
needs_leading_newline = False
if p.exists() and p.stat().st_size > 0:
with open(p, "rb") as rf:
rf.seek(-1, 2) # Read last byte of file
needs_leading_newline = rf.read(1) != b"\n"
with open(p, mode="a", encoding="utf-8") as wf:
prefix = "\n" if needs_leading_newline else ""
wf.write(f"{prefix}{text}\n")
Key Details & Edge Cases
open(..., mode="a")does NOT automatically insert a newline before your string:- Append mode simply positions the file cursor at the end of the file (
EOF). If the previous write ended without\n(e.g.,f.write("first")without\n), your nextf.write("second\n")will produce"firstsecond\n"on the same line unless you either end every write with\nconsistently or check the final byte (rf.seek(-1, 2)) before appending.
- Append mode simply positions the file cursor at the end of the file (
- Never use
mode="w"when appending:- Opening an existing file with
mode="w"immediately truncates its size to0bytes, erasing all previous contents. Always usemode="a"(creates the file if missing, appends to the end if it already exists).
- Opening an existing file with
- Appending multiple lines at once (
"\n".join(lines)vs.f.writelines()):f.writelines(["a", "b"])does not add newlines between strings—it writes"ab". Usef.write("\n".join(lines) + "\n")(whenlinesis non-empty) or loopfor line in lines: print(line, file=f).
- Cross-platform line endings (
\nvs.\r\n):- In text mode (
mode="a"), Python’s universal newlines automatically translate\nin your code to\r\non Windows and\non Linux/macOS. Passnewline="\n"toopen(...)if you want consistent UnixLF(\n) line endings on Windows as well.
- In text mode (
- Concurrency warning (
threading/multiprocessing):- Multiple threads or processes appending concurrently to the same file without a
threading.Lock(or the standard librarylogging.FileHandler, which is thread-safe out of the box) can interleave partial lines.
- Multiple threads or processes appending concurrently to the same file without a
Comparison of Methods for Appending Lines to a File in Python
| Approach | Auto-Appends \n? |
Handles Missing Trailing \n in Existing File? |
Thread-Safe? | Best Used When |
|---|---|---|---|---|
with open(p, "a", encoding="utf-8") as f: print(s, file=f) (Recommended) |
Yes | No (assumes prior lines end with \n) |
No | Standard scripts, logs, and loops where every writer appends complete lines. |
with open(p, "a", encoding="utf-8") as f: f.write(f"{s}\n") (Recommended) |
No (explicit \n in string) |
No | No | High-throughput line writing with explicit control over formatting and line endings. |
append_line(p, s) (checks last byte b"\n") |
Yes | Yes (prepends \n if file lacks trailing newline) |
No | Appending to user-edited files, .env configs, or .gitignore files that may lack a final newline. |
logging.FileHandler(p, mode="a") |
Yes | No | Yes (built-in lock per handler) | Multi-threaded applications writing structured log lines continuously to disk. |
You must log in or register to comment.
