Python Files, Paths, CSV and JSON · Lesson 103 of 149

Python Writing and Appending Files

What you will learn

  • Writing with mode "w" and adding with "a"
  • write(), writelines() and print(..., file=f)
  • The danger that "w" erases the file
  • Mode "x" and the read-write modes
  • Buffering and flush
  • Saving safely with a temporary file

1. Opening for writing

In lesson 15.1 the second argument of open was left out, so the mode was "r" (read). The main text modes:

Mode Meaning If the file exists If it does not exist
"r" read (default) read it error
"w" write erased, then written created
"a" append new text added at the end created
"x" create exclusively error (FileExistsError) created
"r+" read and write kept; writing overwrites from the start error
"w+" read and write erased created

Always add encoding="utf-8" for text (lesson 15.1) and use with so the file is closed (and the text saved to disk) at the end of the block.

2. Writing with "w"

with open("out.txt", "w", encoding="utf-8") as f:
    n = f.write("hello\n")
    print(n)
    f.write("world\n")

print(open("out.txt", encoding="utf-8").read())
6
hello
world

  • f.write(text) writes a string and returns the number of characters written (6 here).
  • write does not add a newline. You must put \n where lines should end:
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("no newline")
    f.write("same line\n")

print(repr(open("out.txt", encoding="utf-8").read()))
'no newlinesame line\n'
  • write accepts only strings. Convert numbers first with str() or an f-string (lesson 4.5):
with open("out.txt", "w", encoding="utf-8") as f:
    f.write(42)
TypeError: write() argument must be str, not int

(Reading back with open(...) and no with, as above, is fine for a short demonstration; in real code use with.)

Quick check: does `f.write("a")` followed by `f.write("b")` give two lines?

No. It gives the single line ab, because write adds no newline.

3. Careful: "w" erases

Opening an existing file in "w" mode empties it at once, before you write anything:

with open("out.txt", "w", encoding="utf-8") as f:
    f.write("fresh\n")

print(repr(open("out.txt", encoding="utf-8").read()))
'fresh\n'

Whatever was in out.txt before is gone. Double-check the name before using "w", especially with a user-supplied path. To add to a file instead, use "a".

4. Appending with "a"

with open("out.txt", "a", encoding="utf-8") as f:
    f.write("added\n")

print(repr(open("out.txt", encoding="utf-8").read()))
'fresh\nadded\n'

The old content stays, and the new text goes at the end. Append is the right mode for logs and for adding records to a growing file.

5. More ways to write

writelines

writelines writes every string in a list or any iterable. It does not add newlines either:

with open("out.txt", "w", encoding="utf-8") as f:
    f.writelines(["a\n", "b\n", "c\n"])

with open("out.txt", "w", encoding="utf-8") as f:
    f.writelines(["a", "b"])

print(repr(open("out.txt", encoding="utf-8").read()))
'ab'

(The second with erased the first result, as section 3 warned.) To write a list of items one per line, join them:

items = ["milk", "eggs", "bread"]
with open("list.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(items) + "\n")

print(open("list.txt", encoding="utf-8").read().split())
['milk', 'eggs', 'bread']

print can write into a file, and then adds the newline for you and converts non-strings:

with open("out.txt", "w", encoding="utf-8") as f:
    print("x", 1, 2.5, file=f)
    print("y", file=f, end="")

print(repr(open("out.txt", encoding="utf-8").read()))
'x 1 2.5\ny'

This is often the easiest way to write formatted lines. Loops with f-strings also work well:

with open("out.txt", "w", encoding="utf-8") as f:
    for i in range(1, 4):
        f.write(f"{i} squared is {i * i}\n")

print(open("out.txt", encoding="utf-8").read(), end="")
1 squared is 1
2 squared is 4
3 squared is 9

Copying with transformation

Two files can be open in one with (lesson 14.6): read one, write the other:

with open("list.txt", encoding="utf-8") as src, open("copy.txt", "w", encoding="utf-8") as dst:
    for line in src:
        dst.write(line.upper())

print(open("copy.txt", encoding="utf-8").read().split())
['MILK', 'EGGS', 'BREAD']

6. "x" and the read-write modes

"x" creates a file and refuses to overwrite an existing one, which makes it safe:

with open("new1.txt", "x") as f:
    f.write("x")

open("new1.txt", "x")
FileExistsError: [Errno 17] File exists: 'new1.txt'

"w+" and "r+" allow both reading and writing, and you move around with seek (lesson 15.1):

with open("rw.txt", "w+", encoding="utf-8") as f:
    f.write("abc")
    f.seek(0)
    print(f.read())

with open("rw.txt", "r+", encoding="utf-8") as f:
    f.write("Z")
    f.seek(0)
    print(f.read())
abc
Zbc

"r+" keeps the file but writing overwrites characters from the current position (the start): a became Z. These modes are rarely needed; most programs read a file, change data in memory, and write the whole file back.

7. Buffering and flush

Writing to disk one character at a time would be slow, so Python collects text in a buffer and writes it in larger pieces. The text may therefore not be in the file yet when you look:

f = open("buf.txt", "w")
f.write("data")
print(open("buf.txt").read() == "")
f.flush()
print(open("buf.txt").read())
f.close()
True
data

f.flush() forces the buffer out; close() (done by with) flushes and closes. If the program crashes before the file is closed, buffered text can be lost. Another reason to use with.

8. Writing safely

If a program crashes while it writes a file with "w", the old content is already gone and the new content is incomplete. For important files, write to a temporary file and then replace the real one in a single step:

import os

with open("tmp.txt", "w", encoding="utf-8") as f:
    f.write("new content\n")
os.replace("tmp.txt", "final.txt")

print(os.path.exists("tmp.txt"), open("final.txt", encoding="utf-8").read().strip())
False new content

os.replace(old, new) renames the file, replacing the destination if it exists. The rename is done by the operating system as a single operation, so a reader sees either the old file or the complete new one. (Lesson 15.4 shows the pathlib way.)

Worked example: a to-do list saved between runs

Three small functions keep tasks in todo.txt, one per line. load returns an empty list the first time, when the file does not exist yet.

FILE = "todo.txt"


def load():
    try:
        with open(FILE, encoding="utf-8") as f:
            return [line.rstrip("\n") for line in f if line.strip()]
    except FileNotFoundError:
        return []


def save(tasks):
    with open(FILE, "w", encoding="utf-8") as f:
        for task in tasks:
            f.write(task + "\n")


def add(task):
    with open(FILE, "a", encoding="utf-8") as f:
        f.write(task + "\n")


print(load())
save(["buy milk", "call Rina"])
add("pay bills")
tasks = load()
print(tasks)
tasks.remove("call Rina")
save(tasks)
print(load())
print(open(FILE, encoding="utf-8").read(), end="")
[]
['buy milk', 'call Rina', 'pay bills']
['buy milk', 'pay bills']
buy milk
pay bills
Piece Idea
except FileNotFoundError: return [] a missing file is a normal first-run situation
if line.strip() in the comprehension skips blank lines
save with "w" rewrites the whole list: right after changing the list in memory
add with "a" adds one line without touching the rest

The tasks are made up. Run the program twice: the second time load() would return the saved tasks, which is the point of files. (Delete todo.txt to start again.)

Common mistakes

  • Opening with "w" and wiping a file you meant to keep.
  • Forgetting \n, so lines run together.
  • Passing numbers to write without converting.
  • Forgetting with or close(), so the data is not saved.
  • Reading a file that is still open for writing, and seeing stale content (buffering).
  • Using "a" when you wanted to replace (the file grows on every run).
  • Missing encoding="utf-8".

Key takeaways

  • "w" writes (and erases an existing file), "a" appends, "x" creates only if new, "r+" and "w+" read and write.
  • write needs strings and adds no newline; writelines adds none either; print(..., file=f) adds one.
  • Always use with, which flushes and closes the file for you.
  • Writing is buffered; flush() pushes text to disk.
  • For important files, write a temporary file and os.replace it over the real one.

Practice

1. What is the difference between "w" and "a"?

Show answer

"w" erases an existing file and starts fresh; "a" keeps the content and adds new text at the end.

2. Write the numbers 1 to 5, one per line, into nums.txt.

Show answer
with open("nums.txt", "w", encoding="utf-8") as f:
    for n in range(1, 6):
        f.write(f"{n}\n")

3. Why does f.write(3.5) fail?

Show answer

write accepts only strings. Use f.write(str(3.5)) or f.write(f"{3.5}").

4. Which mode refuses to overwrite an existing file?

Show answer

"x" (it raises FileExistsError).

5. Why might a file be empty when you open it from another program while yours still has it open?

Show answer

Output is buffered; the text may not have been written yet. flush() or closing the file (via with) writes it.

6. Why write to a temporary file and then use os.replace?

Show answer

If the program crashes during writing, the original file is still intact; the replacement happens in one step, so readers see either the old complete file or the new complete file.