Automate everyday tasks with Python · Lesson 5 of 14

Read and write text files safely

Read and write text files with the right encoding, process them line by line, append to logs and save files without losing data on a crash.

About 14 minutes · code runs in your browser, nothing to install

Text files are everywhere in automation: logs, lists, notes, exported data. You met open() and the with statement statement in Reading and writing files. This lesson adds the habits that keep scripts safe on any computer: always say which encoding to use, work line by line, and never leave a half-written file behind.

Always give the encoding

A file is stored as bytes. The encoding is the rule that turns bytes into letters. Most files today use UTF-8, but if you do not say so, Python uses the computer's default, which on some Windows systems is an older code page. A file written on one machine can then turn into garbage on another. Writing encoding="utf-8" every time avoids that.

Pythoneditable
from pathlib import Path

# A file saved by an old program in the Windows-1252 encoding
Path("old.txt").write_text("Café menu: crème brûlée €4\n", encoding="cp1252")

try:
    text = Path("old.txt").read_text(encoding="utf-8")
except UnicodeDecodeError:
    print("Not valid UTF-8")

text = Path("old.txt").read_text(encoding="cp1252")
print(text.strip())
Output
Not valid UTF-8
Café menu: crème brûlée €4
Tip: If you do not know a file's encoding, try utf-8 first. encoding="utf-8", errors="replace" reads anything and shows a � where a byte does not fit, which is better than crashing in the middle of a batch.

Line by line

Looping over an open file reads one line at a time, so even a huge log file uses little memory. Here we pull the error lines out of a log and save them to their own file.

Pythoneditable
errors = []
with open("app.log", encoding="utf-8") as f:
    for line in f:
        if " ERROR " in line:
            errors.append(line.rstrip("\n"))

with open("errors.txt", "w", encoding="utf-8") as out:
    for line in errors:
        out.write(line + "\n")

print(len(errors), "errors saved")
with open("errors.txt", encoding="utf-8") as f:
    print(f.read().strip())
Output
2 errors saved
2026-03-15 08:02 ERROR disk full
2026-03-15 08:06 ERROR timeout

Appending to a log

Mode "a" adds to the end of a file and creates it if it is missing, which is exactly what you want for a log that grows each time a script runs. print() can write into a file too with file=; it adds the new line for you.

Pythoneditable
def log(message):
    with open("history.txt", "a", encoding="utf-8") as f:
        print(message, file=f)

log("run 1: moved 4 files")
log("run 2: moved 0 files")
log("run 3: moved 2 files")

with open("history.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()
print(lines)
print("last run:", lines[-1])
Output
['run 1: moved 4 files', 'run 2: moved 0 files', 'run 3: moved 2 files']
last run: run 3: moved 2 files
Note: On Windows, every \n you write is stored as two characters (\r\n); on macOS and Linux it stays one. Reading the file in text mode turns both back into \n, so your code works the same. Just do not compare file sizes between systems.

Saving without losing data

If a script crashes while it is writing, the file can be left half empty. A safe pattern is to write a temporary file next to it first and then swap it into place with replace(), which overwrites the old file in one step on every system.

Pythoneditable
from pathlib import Path

def save_safely(path, text):
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    tmp.replace(path)

target = Path("contacts.txt")
save_safely(target, "Lena\nOmar\n")
save_safely(target, "Lena\nOmar\nYuki\n")

print(target.read_text(encoding="utf-8").splitlines())
print(sorted(p.name for p in Path(".").glob("contacts*")))
Output
['Lena', 'Omar', 'Yuki']
['contacts.txt']

✎ Exercise

names.txt is messy: extra spaces, empty lines and a repeated name. Read it, strip each line, skip empty lines and duplicates, sort the names and write them, one per line, to clean.txt. Then print clean.txt.

Hint: A set ignores duplicates. Skip a line when line.strip() is an empty string, then write sorted(names).

Your codewrite your answer, then Run
# your code here

Expected output:

Amir
Bruno
Lena
Zoe
Show a solution
Solutioneditable
names = set()
with open("names.txt", encoding="utf-8") as f:
    for line in f:
        name = line.strip()
        if name:
            names.add(name)

with open("clean.txt", "w", encoding="utf-8") as out:
    for name in sorted(names):
        out.write(name + "\n")

with open("clean.txt", encoding="utf-8") as f:
    print(f.read().strip())
Output
Amir
Bruno
Lena
Zoe

Check yourself

1. Why write encoding="utf-8" when opening text files?

2. What does mode "a" do?

3. Why write to a temporary file and then call replace()?

Spotted a mistake on this page? Tell us