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
easyAnswer
First step
Full solution
- 2 Step 2: Reading: OPEN 'names.txt' FOR READING. WHILE NOT end of file: line = READ line. OUTPUT line. CLOSE file.
- 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.
Example 2
mediumExample 3
mediumExample 4
mediumExample 5
mediumExample 6
mediumExample 7
mediumExample 8
hardExample 9
hardExample 10
challengePractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
hardExample 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
easyExample 10
easyExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
mediumExample 19
mediumExample 20
challengeExample 21
challengeExample 22
challengeExample 23
easyExample 24
easyExample 25
easyExample 26
easyExample 27
mediumExample 28
mediumExample 29
mediumExample 30
mediumExample 31
mediumExample 32
mediumExample 33
hardExample 34
hardExample 35
hardExample 36
challengeRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.