File Operations Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of File Operations.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

The operations of reading data from files and writing data to files on a storage device, allowing programs to persist information beyond a single run.

File operations let your program save and load information โ€” like writing notes in a notebook and reading them later.

Read the full concept explanation โ†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Files provide persistent storage. Without files, all data would be lost when the program ends. Open, read/write, close is the standard pattern.

Common stuck point: Always close files when done (or use with-statements). Unclosed files can lose data or lock the file from other programs.

Worked Examples

Example 1

easy
Write pseudocode to write three names to a file called 'names.txt', then read them back and display them.

Solution

  1. 1
    Step 1: Writing: OPEN 'names.txt' FOR WRITING. WRITE 'Alice'. WRITE 'Bob'. WRITE 'Charlie'. CLOSE file.
  2. 2
    Step 2: Reading: OPEN 'names.txt' FOR READING. WHILE NOT end of file: line = READ line. OUTPUT line. CLOSE file.
  3. 3
    Step 3: Key pattern: always open โ†’ use โ†’ close. Opening for writing creates or overwrites the file. Opening for reading requires the file to exist.

Answer

Write: open, write lines, close. Read: open, read lines in a loop until end of file, close.
File operations allow programs to persist data between runs. The open-use-close pattern ensures resources are properly managed and data is not corrupted.

Example 2

medium
Explain the difference between opening a file in WRITE mode vs APPEND mode. When would you use each?

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
Write pseudocode that reads a file of numbers (one per line), calculates their total, and writes the result to a new file 'total.txt'.

Example 2

hard
A program reads a CSV file where each line has 'name,score' (e.g., 'Alice,85'). Write pseudocode to find the student with the highest score and output their name.

Related Concepts

Background Knowledge

These ideas may be useful before you work through the harder examples.

input output