How to write to a file in Python

· 1 min read · Updated March 16, 2026 · beginner
python files io

The basic pattern uses open with a mode. Always prefer using with to ensure the file closes properly.

Writing text to a file

with open("output.txt", "w") as f:
    f.write("Hello, world!")

The “w” mode creates a new file or overwrites an existing one.

Appending to a file

with open("output.txt", "a") as f:
    f.write("Another line\n")

The “a” mode appends to the end without overwriting.

Writing multiple lines

lines = ["First line\n", "Second line\n", "Third line\n"]

with open("output.txt", "w") as f:
    f.writelines(lines)

Writing binary data

data = b"\x00\x01\x02\x03"

with open("output.bin", "wb") as f:
    f.write(data)

Use “wb” for binary write mode.

See Also