Open the file in append mode using open("file.txt", "a", encoding="utf-8") inside a with context manager and call .write() (remembering to include \n explicitly), or use print("new line", file=f) to append text to the end of the file without overwriting existing content.
Basic Example
# 1. Append a single line using file.write() (include '\n' explicitly)
with open("log.txt", "a", encoding="utf-8") as file:
file.write("2026-11-26 19:14:00 - Service started\n")
# 2. Append multiple lines at once using file.writelines() or "\n".join()
new_entries = [
"2026-11-26 19:14:05 - Connected to database",
"2026-11-26 19:14:10 - Listening on port 8000",
]
with open("log.txt", "a", encoding="utf-8") as file:
file.write("\n".join(new_entries) + "\n")
Key Details & Edge Cases
- Creates the file automatically if it does not exist: Unlike
"r"(read mode), opening a non-existent file with"a"creates an empty file and appends to it rather than raisingFileNotFoundError. - Avoiding glued lines when an existing file lacks a trailing newline: If the existing file ends without a newline (e.g.,
"First line"instead of"First line\n"), callingfile.write("Second line\n")produces"First lineSecond line\n". When appending to arbitrary external files, inspect the last byte first if formatting matters:from pathlib import Path path = Path("notes.txt") needs_leading_newline = path.exists() and path.stat().st_size > 0 and not path.read_bytes().endswith(b"\n") with open(path, "a", encoding="utf-8") as file: if needs_leading_newline: file.write("\n") file.write("Cleanly appended line\n") - Appending AND reading in the same handle (
"a+"): Opening with"a+"lets you both read and append, but the file pointer starts at the end of the file (EOF). Callfile.seek(0)before callingfile.read()—and note that on POSIX/Windows systems, writes in"a+"mode always jump back to EOF regardless of where you seek. - Note on
pathlib.Path:pathlib.Path.write_text()always overwrites ("w") and does not accept amode="a"parameter—usewith path.open("a", encoding="utf-8") as file:when working withPathobjects. - Avoid
"w"when intending to append: Opening an existing file with"w"immediately truncates (erases) its contents to zero bytes before writing anything.
Comparison of File Write & Append Modes
| File Mode | Overwrites Existing Content? | Creates File If Missing? | Initial Pointer Position | Best Used When |
|---|---|---|---|---|
"a" |
No (appends to EOF) | Yes | End of file | Appending log entries, CSV rows, or incremental text output. |
"a+" |
No (writes always go to EOF) | Yes | End of file | Reading existing content (after file.seek(0)) and appending new text. |
"w" |
Yes (truncates to 0 bytes) | Yes | Beginning of file | Replacing a file completely with fresh output. |
"x" |
Fails (FileExistsError) |
Yes (only if new) | Beginning of file | Safely creating a brand-new file without risking accidental overwrites. |
You must log in or register to comment.
