Concepts / Reading and Writing Text Files in Python

Reading and Writing Text Files in Python

A file is data stored in secondary memory.

  • Programming

The Vanishing Budget

Imagine a Python program that calculates a monthly budget. It stores income, expenses, and the remaining balance in variables, then displays the results on screen. The program works correctly, but after you close it, the calculations are no longer available. Where did the data go?

While the program was running, its calculations and variables existed in the computer's CPU and main memory. The CPU performed the work, while main memory held the data structures and intermediate results used by the program. This workspace is active and fast, but it is volatile. If power is lost, the data stored there is erased.

CPU and RAMRunning program dataPower lostData erasedSecondary memoryFiles and drivesPower lostData retainedpower removedpower removed
What happens to program data in the CPU and main memory compared with data stored on secondary memory when power is lost?

Where Program Data Lives

Definition

Main memory, including the CPU and RAM as described in this material, is the place where programs execute and store data while they are running. It is volatile because it requires electrical power; when power is lost, the data in that active workspace disappears.

Definition

Secondary memory includes files, hard drives, solid-state drives, USB flash drives, and other storage devices. It is non-volatile, so data written there remains available even when the power is off.

LocationRole while a program runsWhat happens without power
CPU and main memoryExecutes the program and holds its active dataThe data is erased
Secondary memoryStores files and other persistent dataThe data remains available

The source distinguishes the temporary working area from persistent storage.

Running programCalculations and variablesMain memoryTemporary workspaceFileSecondary memoryLater program runData recoveredstores active dataprogram writes dataprogram reads data
How does data move from a running program in main memory into a file so it can be recovered during a later program run?

Files as Persistent Storage

A file is data stored in secondary memory. When a program explicitly writes information to a file, it moves that information out of the temporary workspace of main memory and into storage that survives the end of the program and the loss of electrical power.

In the real world

Think of main memory as a whiteboard used while solving a problem. You can work on the whiteboard while the program is active, but its contents do not provide a lasting record when the active session ends. A file is like writing the final answer in a notebook and placing that notebook on a shelf. The notebook remains available for a later session.

Worked example

Saving a Monthly Budget

A budget program calculates income, expenses, and a remaining balance. How can the results remain available after the program closes?

  1. 1
    Calculate

    While the program runs, the calculations and their results are held in variables in the CPU and main memory.

  2. 2
    Write

    The program explicitly writes the budget result to a file in secondary memory instead of only displaying it on screen.

  3. 3
    Close

    The program ends, so its active data in main memory is no longer available.

  4. 4
    Read later

    During a later run, the program can read the file and see the previously calculated budget result.

Result

The result persists because it was written to a file in non-volatile secondary memory.

Python programWritingMain memoryActive dataText fileReadable stored textPython programReadingMain memoryRecovered textwriteread laterrestore data
What is the sequence of steps when a Python program writes text to a file and later reads that text back into memory?

Text and Database Files

Text files contain plain text made from readable letters, numbers, and punctuation. When opened in a text editor such as Notepad or VS Code, their actual content can be viewed directly. Examples include CSV budget data, program log files, and configuration files.

Binary database files use a structured format intended for database software rather than direct reading in a text editor. A database file may organize many records in tables and include relationships, indexes for searching, and other internal structures. The database software acts as the intermediary through which you work with that file.

Text filePlain textText editorContent readable directlyDatabase fileStructured binary formatDatabase softwareIntermediaryopen directlyuse through
What is the difference between human-readable text files and structured binary database files?
FeatureText fileBinary database file
RepresentationReadable plain textStructured binary format
Direct viewingCan be read in a text editorNot intended to be read in a text editor
Typical useCSV data, logs, and configuration settingsRecords, tables, relationships, and indexes
How it is accessedA program can read and write the textDatabase software is used as an intermediary

The two categories serve different storage and access purposes.

Power Loss and Recovery

Power loss exposes the difference between temporary program state and persistent file data. Before power is removed, a running program may have calculations and variables in CPU and main memory, while a file may hold data in secondary memory. After power is removed, the active CPU and main-memory data is erased. Data that was written to secondary memory remains available.

Program dataCPU and RAMProgram dataErasedStored fileSecondary memoryStored fileStill availablePower lossaffects volatile datadoes not erase non-volatile data
What changes when power is removed, and which stored data remains available?
  • Common mistake

    Assuming that a value shown on screen has automatically been saved.

    What it looks like

    A budget program displays the remaining balance and then closes.

    Why it fails

    Displaying a result does not move it from the temporary program workspace into secondary memory.

    Do this instead

    Explicitly write the data to a file when it must survive the program's execution.

  • Common mistake

    Expecting variables to remember their values during a later program run.

    What it looks like

    The program is restarted and is expected to know yesterday's calculations.

    Why it fails

    The variables belonged to the earlier running program and were held in volatile CPU and main memory.

    Do this instead

    Save the required data in a file and read that file during the later run.

  • Common mistake

    Treating a binary database file as though it were a plain text document.

    What it looks like

    Opening a database file in a text editor and expecting readable records.

    Why it fails

    Binary database files use structured formats intended for database software.

    Do this instead

    Use database software as the intermediary for interacting with the database file.

Persistence Practice

EASY

A game calculates a player's progress while running. Decide what must happen if the progress should still be available after the program closes. Then classify the storage involved at each stage: the active calculation, the saved record, and the later recovery.

Hints
  • Ask where the active calculation is held while the program runs.
  • Ask what action moves the progress into non-volatile storage.
  • Ask how a later program run can obtain the saved progress.
Worked example

Checking the Storage Path

A program calculates a result, writes it to a text file, loses power, and is started again. Which parts of the result can remain available?

  1. 1
    During calculation

    The active result is held in the CPU and main memory, where the running program executes.

  2. 2
    After writing

    The written copy is stored in a file in secondary memory.

  3. 3
    After power loss

    The active copy in volatile memory is erased, while the file remains available.

  4. 4
    During recovery

    The later program run can read the file and recover the stored result.

Result

Only the copy written to the file is persistent across power loss and program runs.

Lasting Program State

  1. 1
    The CPU and main memory are the active workspace for a running program, but they are volatile.
  2. 2
    When power is lost, data held only in the CPU and main memory is erased.
  3. 3
    Secondary memory is non-volatile, so files stored there remain available without power.
  4. 4
    A program must explicitly write data to a file for that data to persist beyond the program's execution.
  5. 5
    Text files contain readable plain text, while binary database files use structured formats accessed through database software.

Key Takeaways

  • Running programs use the CPU and main memory as a fast but volatile workspace.
  • Power loss erases data that exists only in CPU and main memory.
  • Files store data in non-volatile secondary memory, allowing it to persist across program runs.
  • Text files hold readable plain text, whereas binary database files are structured for specialized database software.
  • Reading and writing files connects temporary program activity with persistent stored data.

Related concepts

More concepts starting with R