How to Read and Write Text Files in Python

This code provides simple helper functions to save and load text files using Python's standard pathlib library.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

22 lines
Python 3.9+
from pathlib import Path


def save_text_data(filename: str, content: str) -> None:
    file_path = Path(filename)
    file_path.write_text(content, encoding="utf-8")


def load_text_data(filename: str) -> str:
    file_path = Path(filename)
    return file_path.read_text(encoding="utf-8")


if __name__ == "__main__":
    filename = "example_data.txt"
    data_to_save = "Hello, this is beginner-friendly file data!\nSecond line here."

    save_text_data(filename, data_to_save)
    loaded_data = load_text_data(filename)

    print("Saved and loaded content:")
    print(loaded_data)

Output

stdout
Saved and loaded content:
Hello, this is beginner-friendly file data!
Second line here.

How it works

The save_text_data function uses Path.write_text to create or overwrite a file with the given content, specifying UTF-8 encoding for universal compatibility. The load_text_data function uses Path.read_text to read the entire file content as a string. These methods are concise and handle file opening and closing automatically, reducing boilerplate. The if __name__ == "__main__" guard ensures the test code only runs when the script is executed directly, not when imported as a module.

Common mistakes

  • Forgetting to specify encoding, which can cause UnicodeDecodeError on systems with different default encodings
  • Using `open()` without a context manager, risking file handles not being closed properly
  • Assuming the file exists before reading without checking, leading to FileNotFoundError

Variations

  1. Use `open(filename, 'w')` and `open(filename, 'r')` with `with` statements for more explicit control
  2. Use `Path.write_bytes` and `Path.read_bytes` for binary data

Real-world use cases

  • Persisting user preferences or application settings to a local text file
  • Storing logs or small amounts of data from a script for later analysis
  • Saving intermediate results in a data processing pipeline to a temporary file

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.