Sub topic 5
Writing and Appending Text
This chapter assumes you know how open() returns a file object, what the mode letters mean, and why the with statement is the standard way to close files. It also assumes you can use try/except. Here you will learn how text gets from your program into a file, and what differs between "w", "a" and "x".
What write() actually does
A file opened in a text write mode ("w", "a" or "x") accepts str objects through two methods: write() and writelines(). The example below creates a file, writes one string, then writes a list of strings.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
f.writelines(["second line\n", "third line\n"])Three facts about these methods cause most beginner bugs.
write()takes exactly onestrand returns the number of characters written. It does not add a newline.writelines()takes any iterable ofstr. Despite the name, it does not add newlines either. Each item must already end in"\n"if you want separate lines.- Neither method accepts numbers,
None, orbytesin a text-mode file. Convert values yourself.
The return value of write() is rarely needed, but it shows what the method counts:
with open("count.txt", "w", encoding="utf-8") as f:
n = f.write("h\u00e9llo\n")
print(n)This prints 6. The count is in characters, not bytes. The letter é is one character but takes two bytes in UTF-8, so the file on disk is 7 bytes long. Encodings get their own chapter. For now, remember that the return value does not tell you the file size.
Building lines correctly
Because nothing adds line endings for you, you must decide where each line ends. Here are three common ways to do it.
names = ["Ada", "Linus", "Grace"]
with open("names.txt", "w", encoding="utf-8") as f:
# 1. Explicit newline in an f-string, one write per item
for name in names:
f.write(f"{name}\n")
with open("names2.txt", "w", encoding="utf-8") as f:
# 2. writelines with a generator expression: no intermediate list
f.writelines(f"{name}\n" for name in names)
with open("names3.txt", "w", encoding="utf-8") as f:
# 3. print() with file=: adds the newline for you
for name in names:
print(name, file=f)All three produce the same file. Choose by context:
| Approach | Adds newline | Converts non-strings | Good for |
|---|---|---|---|
| `f.write(s)` | No | No, raises `TypeError` | One piece of text at a time |
| `f.writelines(it)` | No | No, raises `TypeError` | Many prepared strings, including generators |
| `print(x, file=f)` | Yes, controlled by `end=` | Yes, calls `str()` | Mixed values, quick report output |
print() is convenient because it calls str() on each argument and joins them with sep. It is also slightly slower than write() in tight loops, which rarely matters.
A frequent mistake is joining lines with "\n".join(lines) and writing the result. This leaves out the final newline. Text files conventionally end with one, and many tools expect it. Add it back:
lines = ["alpha", "beta", "gamma"]
with open("greek.txt", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")If lines can be empty, this writes a single blank line. Guard for that case if it matters, or use writelines with per-item newlines, which writes nothing for an empty list.
What "w" does to existing data
The mode "w" truncates the file at the moment open() succeeds, before you write anything. If report.txt held 10 MB yesterday, it is empty the instant this line runs:
f = open("report.txt", "w", encoding="utf-8")If your program then crashes while it computes the new content, the old content is gone and the new content never arrived. Two patterns reduce this risk:
- Compute everything first, then open the file and write. This shortens the dangerous window but does not remove it.
- Use a temporary file and swap it into place, which a later chapter covers.
The mode "w" creates the file if it is missing, but it does not create missing directories. Opening "out/result.txt" for writing when out/ does not exist raises FileNotFoundError. Opening a path that is a directory raises IsADirectoryError.
Appending with "a"
Append mode opens the file without truncating it and sends every write to the end. If the file does not exist, it is created.
with open("notes.txt", "a", encoding="utf-8") as f:
f.write("appended line\n")Append mode is the natural choice for logs, audit trails and any file that grows over time. Two details matter:
- Writes always go to the end, even if you call
seek()first. On POSIX systems this comes from the operating system'sO_APPENDflag. You cannot use append mode to overwrite the middle of a file. - Python does not insert a newline before your text. If the existing file does not end with
"\n", your appended text continues on the same line as the old last line. A log writer that always ends each record with"\n"avoids the problem.
Here is a small append-based logger:
from datetime import datetime, timezone
def log(message, path="app.log"):
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
with open(path, "a", encoding="utf-8") as f:
f.write(f"{stamp} {message}\n")
log("service started")
log("job finished")Opening and closing the file on every call is simple and safe. It also means each message reaches the file as soon as the with block exits. For very high write rates you would keep the file open, which brings up buffering.
Exclusive creation with "x"
The mode "x" creates a new file and fails with FileExistsError if the path already exists. Use it when overwriting would be a bug, such as generating a report with a fixed name.
try:
with open("report.txt", "x", encoding="utf-8") as f:
f.write("draft\n")
except FileExistsError:
print("report.txt already exists; not overwriting")The check and the creation happen as one operation inside the operating system. This is safer than testing os.path.exists() first, because another process could create the file between your test and your open().
Choosing between the three modes
Buffering: when does the text reach the disk?
Calling write() does not send bytes to the disk immediately. Python collects text in an in-memory buffer and hands it to the operating system in larger pieces. The operating system also keeps its own cache. This makes writing fast, but it has consequences:
- Text is guaranteed to be passed to the operating system when you call
flush()or when the file closes. Thewithblock closes the file, so leaving it flushes the buffer. - If your program is killed with the file still open, buffered text can be lost.
- Another program reading the file while you are still writing may see only part of what you have written so far.
To make progress visible to other readers, flush after each message:
import time
with open("progress.log", "a", encoding="utf-8") as f:
for step in range(3):
f.write(f"step {step} done\n")
f.flush()
time.sleep(1)flush() moves text from Python's buffer to the operating system. It does not force the operating system to write to the physical disk. That requires os.fsync(f.fileno()), which you will see in the chapter on safe writes. It is slow, so use it only when losing the last few records after a power failure would be a real problem.
Newlines when writing
In text mode you always write "\n" for a line break. By default, Python translates it to the platform's line separator as it writes: "\n" on Linux and macOS, "\r\n" on Windows. Do not write "\r\n" yourself in a text-mode file. On Windows it would become "\r\r\n". The newline argument of open() controls this translation, and the next chapter covers it along with encodings.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: write() argument must be str, not int` | Passed a number or other non-string | Use `str(x)`, an f-string, or `print(x, file=f)` |
| All lines run together | No `"\n"` in `write()` or `writelines()` items | Add the newline to each item |
| Old file content disappeared | Opened with `"w"` instead of `"a"` | Choose the mode from the diagram above |
| `FileNotFoundError` on a write | The parent directory does not exist | Create it with `Path.parent.mkdir(parents=True, exist_ok=True)` |
| `ValueError: I/O operation on closed file` | Wrote after the `with` block ended | Keep all writes inside the block |
| Last records missing after a crash | Text was still in the buffer | Use `flush()`, or close the file sooner |
| Appended text joins the old last line | The file did not end with a newline | End every record with `"\n"` |
The ValueError is easy to trigger by accident:
with open("temp.txt", "w", encoding="utf-8") as f:
f.write("inside\n")
f.write("outside\n")The last line raises ValueError: I/O operation on closed file. The file object still exists after the block, but it is closed.
Writing from a stream of data
Because writelines() accepts any iterable, you can write data too large for memory without ever building a list. This example writes a million lines while holding only one at a time.
def numbered_lines(count):
for n in range(count):
yield f"line {n}\n"
with open("big.txt", "w", encoding="utf-8") as f:
f.writelines(numbered_lines(1_000_000))Python's buffer keeps memory use flat, and the file grows as the generator produces lines.
Summary of rules
- Always include
"\n"yourself, or useprint(..., file=f). - Choose
"w","a"or"x"by asking what should happen to existing content. - Give every text file an explicit
encoding. - Keep all writes inside the
withblock. - Call
flush()when other readers need to see progress, and expect unflushed text to be lost on a crash.
Exercise
A script writes results with f.writelines(["a", "b", "c"]) and the file contains abc on one line. Why, and what is the smallest change that puts each item on its own line?
Show answer
writelines() does not add line endings. It writes the items back to back. Add the newline to each item, for example f.writelines(item + "\n" for item in ["a", "b", "c"]), or write the list items as ["a\n", "b\n", "c\n"].
Exercise
Write a function append_record(path, text) that appends text as one line to a UTF-8 file, creating the file if needed. It must still produce correct output if text already ends with a newline, so that no blank lines appear. Then say what happens to a call made against a file whose directory does not exist.
Show answer
Code:
def append_record(path, text):
with open(path, "a", encoding="utf-8") as f:
f.write(text.rstrip("\n") + "\n")
(Indent the body by four spaces when you write it.) Stripping any trailing newlines and adding exactly one guarantees one newline per record. If the directory does not exist, open() raises FileNotFoundError, because append mode creates the file but not its parent directories.