iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Write/Create Files

Open with mode 'w', 'a', or 'x' to write. 'w' wipes the file first — be careful.

Overwrite

PYTHON
with open('hello.txt', 'w') as f:
    f.write('first line\n')
    f.write('second line\n')

Append

PYTHON
with open('log.txt', 'a') as f:
    f.write('another entry\n')

Write only if missing

PYTHON
try:
    with open('config.json', 'x') as f:
        f.write('{}')
except FileExistsError:
    print('config already exists — leaving it alone')

Many lines at once

PYTHON
lines = ['one\n', 'two\n', 'three\n']
with open('numbers.txt', 'w') as f:
    f.writelines(lines)    # NB: does NOT add newlines for you

Print to a file

PYTHON
with open('out.txt', 'w') as f:
    print('hello', file=f)
    print('world', file=f)

Atomic writes

If a write must either fully succeed or not happen at all, write to a temp file then rename:

PYTHON
import os, tempfile
with tempfile.NamedTemporaryFile('w', delete=False) as tmp:
    tmp.write(payload)
    tmp_name = tmp.name
os.replace(tmp_name, 'data.json')  # atomic on POSIX
Tip: Always specify encoding='utf-8' for text writes. The platform default (cp1252 on Windows) silently corrupts non-ASCII.

Example

Example
# 'w' overwrites; 'a' appends; 'x' fails if file exists.
# with open('hello.txt', 'w') as f:
#     f.write('first line\n')
#     f.write('second line\n')
print('Open with mode w/a/x to write.')
Try it Yourself »

Exercise

Open a file to append (not overwrite).

open('log.txt', )

Test yourself

Q1. For "create only if missing" use mode…
Q2. writelines adds newlines for you?
Q3. For atomic writes use…

Discussion

Loading…