Reading and Writing Files: Real Operations and Modes

Keep a report after the program ends

A school total in a variable disappears when the process ends. Saving a report to a file makes it available to a later run, but writing can also replace old content or fail.

Reading brings stored bytes into a program; writing sends bytes to storage. A file format and encoding define how those bytes represent the report.

  1. Run a real workflow

    Identify write and read operations on a file.

  2. Choose a mode

    Distinguish replacement from appending and exclusive creation.

  3. Manage resources

    Use structured cleanup and handle failures deliberately.

Save text, then read it in another operation

  1. Program data

    Create report text.

    Maya: 75
  2. Storage operation

    Write encoded content to a named file.

    report.txt
  3. Read operation

    Decode the stored bytes back to text.

    Maya: 75
Read these stages alongside the complete example. They explain the relationship; they do not execute code.

The API defines the mode and resource lifetime

Opening selects a file and a mode. Python r reads an existing file, w writes by replacing its contents, a appends and x creates a new file only if it does not already exist.

Python with closes the file when the block exits during ordinary completion or exception unwinding. Specify the text encoding rather than relying on an environment default. The code below uses a temporary exercise directory you create yourself.

Before starting, review explicit resource cleanup. These examples use JavaScript; other languages can use different syntax and rules.

Write and read an actual report file

This complete example uses Python 3, not JavaScript. Save it as save_report.py in a disposable exercise directory and run python3 save_report.py. It creates or replaces report.txt in the current working directory.

with open('report.txt', 'w', encoding='utf-8') as report:
    report.write('Maya: 75\n')

with open('report.txt', 'r', encoding='utf-8') as report:
    text = report.read()

print(text.strip())

Expected output: Maya: 75. write stores the text, read retrieves it, and strip removes surrounding whitespace for this display. The lesson page does not execute filesystem access. Use only an exercise file you intend to replace.

Compare the sequence with a local data model

This JavaScript Map illustrates storing under a name and reading back. It does not create a disk file, survive process exit or simulate file permissions.

The actual Python operation above comes first because this model teaches the sequence rather than replacing a real file API.

JavaScript · local teaching example

const modelFiles = new Map();
modelFiles.set('report.txt', 'Maya: 75');
console.log(modelFiles.get('report.txt'));

Expected output

Maya: 75

Append a second report line deliberately

This Python 3 example first creates a known exercise file, then appends Ravi’s line. The whole program is shown so it does not rely on a previous section’s execution.

with open('report.txt', 'w', encoding='utf-8') as report:
    report.write('Maya: 75\n')
with open('report.txt', 'a', encoding='utf-8') as report:
    report.write('Ravi: 70\n')
with open('report.txt', 'r', encoding='utf-8') as report:
    print(report.read().strip())

Expected output: Maya: 75, followed by Ravi: 70 on the next line. Repeated append operations add content; they do not deduplicate reports automatically.

Apply the rule to a small change

In the local JavaScript model, store Maya’s report and then replace it with the corrected total 80. Predict the read result and explain the file-mode analogy.

Worked answer

The read returns Maya: 80 because the same key’s value was replaced. This models replacement semantics only; real write modes, failures and storage durability come from the actual API.

JavaScript · local teaching example

const modelFiles = new Map();
modelFiles.set('report.txt', 'Maya: 75');
modelFiles.set('report.txt', 'Maya: 80');
console.log(modelFiles.get('report.txt'));

Expected output

Maya: 80

Recognize mistakes and limits

Replacement mode can destroy earlier content. Confirm the exercise path and choose append or exclusive creation when that matches the requirement. Reading an entire large file into memory may be unsuitable; streaming can process chunks instead.

A completed write call does not by itself establish every crash-durability guarantee. Files can be missing, inaccessible or only partially written. Atomic replacement and durable storage require the relevant API and filesystem semantics.

For the language or tool rules used here, see Python file modes and encodings.

Check the core idea

What does Python mode w do to an existing exercise file?
Choose one answer. You can try again.

Answer and explanation

Opens for writing and replaces the existing contents.

Yes. That is why the path and mode need deliberate choice.

Apply the idea to a new situation

JavaScript · code for this question

const modelFiles = new Map();
modelFiles.set('report.txt', 'Maya: 75');
console.log(modelFiles.get('report.txt'));
Does the JavaScript Map create report.txt on disk?
Choose one answer. You can try again.

Answer and explanation

No; it is an explicitly labeled local model.

Yes. The Python section shows real file operations.

Choose the path, mode and cleanup policy together

File operations move bytes between program and storage. Real APIs define modes, encoding, cleanup and failure behavior; an in-memory model only explains the sequence.

Connect this idea with encoding and byte formats and file-operation failures.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Text and Binary Files: Encoding and Bytes →