Lesson 26 of 30

In progress

Course progress

Python

Read and write files safely

Open files with a context manager, choose the right mode and encoding, and avoid the two mistakes that destroy data.

A program that forgets everything when it exits is a calculator. Files are how your work survives, and the two ways to lose data are opening with the wrong mode and forgetting to close.

What you will learn

  • Open files with with so they always close.
  • Choose r, w and a, and set UTF-8 explicitly.
  • Read line by line without loading a huge file into memory.

Open with a context manager

open() returns a file object. The with statement closes it when the block ends, even if an exception is raised inside.

with open("notes.txt", "r", encoding="utf-8") as handle:
text = handle.read()
print(text)

That shape is the one to memorise: mode, encoding, as handle, indented body. Calling handle.close() by hand works but is skipped whenever an exception escapes, which is exactly when a half-written file is most likely.

Always pass encoding="utf-8". Without it, Python uses the operating system’s default, which differs between Windows and Linux and mangles non-English text. The third argument costs nothing and prevents a whole class of bugs.

Modes decide what happens to existing data

  • "r" reads and fails with FileNotFoundError if the file is absent.
  • "w" writes and truncates an existing file to nothing before writing.
  • "a" appends, creating the file if needed and keeping what is there.
  • "x" creates and fails if the file already exists, which is the safe choice for new output.

The "w" mode is the dangerous one: opening a file you meant to read with "w" empties it immediately, before you write anything.

with open("log.txt", "a", encoding="utf-8") as handle:
handle.write("Startedn")

write does not add a newline. If you want each entry on its own line, include n yourself. print(..., file=handle) does add one, which is often more convenient.

Read by line, not always whole

read() returns the entire file as one string. readlines() returns a list of lines. Iterating the file object yields one line at a time, which keeps memory flat for large files.

with open("scores.txt", encoding="utf-8") as handle:
for line in handle:
name, score = line.strip().split(",")
print(name, int(score))

Each line still carries its trailing newline, so strip() before splitting is not optional. Splitting on a comma assumes every line has exactly two fields; real files need a guard, which is where try and except ValueError earn their place.

This page’s runner has a small in-memory filesystem, so the examples below use a string buffer to show the same read loop without touching disk.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

StringIO behaves like a text file object. Code written against it can later receive a real file handle with no changes, which is also how you test file logic without creating files.

pathlib is the modern shorthand

Path.read_text and Path.write_text handle open, close and encoding for the common cases.

from pathlib import Path
path = Path("notes.txt")
path.write_text("hellon", encoding="utf-8")
print(path.read_text(encoding="utf-8"))
print(path.exists())

For line-by-line processing, path.open() returns a normal file object and works with with. Use pathlib for new code: joining paths with / avoids separator bugs, and exists, suffix and parent are clearer than string slicing.

Handle the missing file

FileNotFoundError is a normal outcome when the user names a path. Catch it where a missing file is expected, and let permission errors surface.

from pathlib import Path
path = Path("settings.txt")
try:
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
text = ""
print(repr(text))

The empty default is a policy decision. For settings, "no file means defaults" is reasonable. For a data file, silently starting empty could overwrite real data on the next save, so raising is safer.

Writing directly to the file you are reading from truncates it before you can read it. The usual safe pattern is to write to data.tmp, close it, then replace the original with Path("data.tmp").replace("data.json"). The replace is atomic on the same filesystem, so a crash leaves either the old file or the new one, never half of each.

Using StringIO, read three lines of name,score pairs, skip any line that does not split into exactly two parts, and print the average score. Then write the valid names to a second buffer, one per line.

Show solution
Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Skipping a malformed line keeps one bad row from stopping the report. The count of valid records is what makes the average meaningful, so print it when the input is untrusted.

Recap

  • with open(...) guarantees the file closes; pass encoding="utf-8" every time.
  • "w" truncates, "a" appends, "x" refuses to overwrite; write does not add a newline.
  • Iterate line by line for large files, and write via a temporary file when replacing data.

Next, you will store structured data in JSON instead of inventing your own text format.

Why does my file look empty after writing?
The data may still be buffered. The `with` block flushes and closes on exit, so read the file after the block ends, not inside it. If you must read inside, call `handle.flush()` first.
Can I open a file without a path?
Yes, a bare name is relative to the current working directory, which is wherever the script was started. That is why a script can work in your editor and fail from a terminal in another folder; use `Path(__file__).parent` to anchor paths to the script.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.