OSPython.007: Reading and Writing Files

Original technical cover illustrating file reading, writing, and data flow

Open-Source Python Lesson #7 introduces file input and output. After learning exceptions in Lesson #6, the next practical step is saving information to disk and reading it back.

Open a file safely

Python’s with statement is a clean way to work with files because the file is closed when the block finishes.

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Hello from Python!\n")

Read the file

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

print(text)

The mode r reads a file. The mode w writes a file and replaces existing contents. The mode a appends new information to the end.

Append another line

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("Second line\n")

Technician exercise

Create a small equipment log. Write a device name and status to equipment.txt, append a second device, then read the entire file and print it. This same basic pattern can later support logs, configuration files, test results, and automation scripts.

Video reference

Video reference: a practical demonstration of Python file handling, including reading, writing, appending, and the with statement.

Key takeaway

Use with open(...) to manage a file, choose the correct mode for reading or writing, and keep the first programs small enough that you can inspect the resulting file yourself.

4 responses to “OSPython.007: Reading and Writing Files”

  1. […] OSPython.008 introduces modules and imports. The goal is to reuse a function without copying it into every script. Begin with OSPython.001: Functions, Parameters, and Return Values and OSPython.007: Reading and Writing Files. […]

    Like

  2. […] OSPython.007: Reading and Writing Files introduced file operations. This lesson explains why the with open(…) pattern is so useful: the file object is a context manager that handles its exit behavior for you. […]

    Like

  3. […] you are inspecting the log with Python, the earlier file reading and writing lesson covers basic file access. Never place passwords, API keys, authentication tokens, or other secrets […]

    Like

  4. […] and formatter objects usually make the design easier to understand. The same principle applies to reading and writing files: simple programs can stay simple, while larger programs benefit from clearer separation of […]

    Like

Leave a Reply