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. The standard pattern is: open the file, read from or write to it, then close the file to ensure data is saved properly.

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.

Sense of Study hint: When working with files, always use the open-read/write-close pattern. In Python, use 'with open(filename) as f:' to automatically close the file when done. Specify the mode: 'r' for reading, 'w' for writing (overwrites), and 'a' for appending.

Worked Examples

Example 1

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

Answer

Write: open, write lines, close. Read: open, read lines in a loop until end of file, close.

First step

1
Step 1: Writing: OPEN 'names.txt' FOR WRITING. WRITE 'Alice'. WRITE 'Bob'. WRITE 'Charlie'. CLOSE file.

Full solution

  1. 2
    Step 2: Reading: OPEN 'names.txt' FOR READING. WHILE NOT end of file: line = READ line. OUTPUT line. CLOSE file.
  2. 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.
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?

Example 3

medium
Trace: 'data.txt' contains 'foo'. Code: open 'a', write 'bar'; close. open 'a', write 'baz'; close. Final contents?

Example 4

medium
Trace: 'x.txt' contains 'OLD'. open 'w', write 'NEW'; close. open 'r', read all; close. What was read?

Example 5

medium
Write pseudocode to count the lines in 'data.txt'. What is the standard pattern?

Example 6

medium
Write pseudocode that copies 'src.txt' to 'dst.txt'. What is the I/O pattern?

Example 7

medium
Trace across three runs: each run opens 'count.txt' in 'a' and writes '1'. After three runs, what does 'count.txt' contain?

Example 8

hard
Write pseudocode that reads 'prices.txt' (one number per line), computes the average, and writes it to 'avg.txt'.

Example 9

hard
Trace: 'students.csv' has lines 'Ana,90' and 'Bo,75'. Code reads each line, splits on ',', tracks the highest score, and outputs the name. What is output?

Example 10

challenge
Design: a program must safely overwrite 'data.json' but never leave it half-written if it crashes mid-write. Describe the standard safe-write pattern in 3 steps.

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.

Example 3

easy
What is the standard three-step pattern for file operations?

Example 4

easy
Which mode ERASES existing file content when opened: 'r', 'w', or 'a'?

Example 5

easy
Which mode ADDS to the end without erasing: 'r', 'w', or 'a'?

Example 6

easy
A file 'data.txt' contains 'hello'. It is opened with mode 'w' and 'bye' is written. What does the file contain now?

Example 7

easy
A file 'data.txt' contains 'hello'. It is opened with mode 'a' and 'bye' is written. Contents now?

Example 8

easy
What error typically occurs if you open a non-existent file in read mode 'r'?

Example 9

easy
Why must files be closed after use?

Example 10

easy
Which mode would you use to simply read a config file without changing it: 'r', 'w', or 'a'?

Example 11

medium
Trace: 'log.txt' is empty. Code: open 'a', write 'A'; close. open 'a', write 'B'; close. Final contents?

Example 12

medium
Trace: 'x.txt' contains 'ABC'. open 'w', write 'D'; close. open 'a', write 'E'; close. Final contents?

Example 13

medium
A file has three lines: 'a','b','c'. Reading all lines into a list, what is the length of that list?

Example 14

medium
Trace: 'n.txt' contains '5'. Code reads the text, converts to int, adds 3, writes the result back with 'w'. Final contents?

Example 15

medium
If you open a file with 'w', write nothing, and close it, what happens to a previously non-empty file?

Example 16

medium
Which mode creates the file if it does not exist AND lets you write: 'r' or 'w'?

Example 17

medium
Code writes 'A' to a file but the program crashes before close (no flush). The file may appear empty on disk. Why?

Example 18

medium
A program opens the same file 'r' twice without closing between, on a system with a low open-file limit, repeatedly in a loop. What failure mode appears?

Example 19

medium
Using `with open('f.txt','w') as fh: fh.write('hi')`, is fh closed after the block, and does it create the file if missing?

Example 20

challenge
Trace across runs: program does open 'a' and writes a line 'run' each run. After running the program 4 times, how many lines does the file contain?

Example 21

challenge
A robust file read should handle a missing file. Outline the control structure (in words) and state what it returns if the file is absent, given a default of empty string.

Example 22

challenge
A file contains '10\n20\n30'. The program reads all lines, converts each to int, and sums them. What is the sum, and what subtle bug could a trailing newline cause?

Example 23

easy
Which mode opens a file for reading only without modifying it?

Example 24

easy
A file 'log.txt' currently contains 'XYZ'. The program opens it with mode 'w' and writes nothing, then closes it. What does 'log.txt' contain afterward?

Example 25

easy
You want to add a new event to the end of a log without losing old events. Which mode do you use?

Example 26

easy
Which of these is the safest way to make sure a file gets closed even if an error occurs: (A) call close at end, (B) use a with-block, (C) never close it?

Example 27

medium
A file 'scores.txt' contains '10\n20\n30\n'. The program reads all lines and counts how many there are. How many lines?

Example 28

medium
Trace: 'sum.txt' contains '4\n5\n6'. Code reads each line, converts to int, sums them, and writes the total back with mode 'w'. Final contents of 'sum.txt'?

Example 29

medium
A program opens 'config.json' but never closes it, in a long-running loop. What resource problem can develop?

Example 30

medium
Why does reading a numeric value from a file usually require an int() conversion?

Example 31

medium
A CSV line reads 'Bob,42,USA'. After splitting on ',', what is the index of '42' and what is its type?

Example 32

medium
You meant to APPEND a new entry to a log but typed mode 'w'. The program runs once. What happened to the log's previous entries?

Example 33

hard
A program reads a 1 GB log file by calling read() once and loading everything into memory. Why is this a poor pattern, and what is the standard alternative?

Example 34

hard
A robust function read_or_default(path, default) should return file contents if present, else the default value. What control structure handles this?

Example 35

hard
A file 'nums.txt' contains '7\n14\n21\n'. Code reads each line, strips whitespace, converts to int, and sums. What is the sum, and why is strip() needed before int()?

Example 36

challenge
Two programs open 'counter.txt' simultaneously, each reads the value 5, increments, and writes 6. What well-known concurrency bug occurred, and how would you prevent it?

Related Concepts

Background Knowledge

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

input output