SyntaxStudy
Sign Up
Python Beginner 8 min read

Writing Files

Writing Files

Use mode "w" to create/overwrite, "a" to append, and "x" to create exclusively (fails if file exists).

Writing Text

with open("output.txt", "w", encoding="utf-8") as f:
    f.write("Hello, World!\n")
    f.write("Second line\n")

writelines()

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)   # no newline added automatically

print() to File

with open("output.txt", "w", encoding="utf-8") as f:
    print("Hello", file=f)
    print(f"Pi = {3.14159:.4f}", file=f)

Append Mode

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("New log entry\n")   # adds to end, never overwrites

Exclusive Creation

try:
    with open("new.txt", "x", encoding="utf-8") as f:
        f.write("Brand new file")
except FileExistsError:
    print("File already exists!")
Example
import os

with open("numbers.txt", "w", encoding="utf-8") as f:
    for i in range(1, 11):
        f.write(f"{i}
")

with open("numbers.txt", "a", encoding="utf-8") as f:
    f.write("--- done ---
")

with open("numbers.txt", "r", encoding="utf-8") as f:
    print(f.read())

os.remove("numbers.txt")
Pro Tip

Mode "w" silently overwrites existing files. If you want to protect existing data, check os.path.exists() first or use mode "x".