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
easySolution
- 1 Step 1: Writing: OPEN 'names.txt' FOR WRITING. WRITE 'Alice'. WRITE 'Bob'. WRITE 'Charlie'. CLOSE file.
- 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.
Answer
Example 2
mediumPractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
hardRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.