File Operations CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

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

Solution

  1. 1
    Step 1: WRITE mode creates a new file or overwrites an existing one โ€” all previous content is deleted.
  2. 2
    Step 2: APPEND mode opens an existing file and adds new content at the end โ€” previous content is preserved.
  3. 3
    Step 3: Use WRITE when generating a fresh file (e.g., saving a document). Use APPEND when adding to existing data (e.g., logging events, adding high scores).

Answer

WRITE overwrites the file; APPEND adds to the end. Use WRITE for fresh output, APPEND for accumulating data.
Choosing the wrong file mode is a common bug โ€” accidentally using WRITE mode can destroy existing data. APPEND mode is safer when you want to preserve previous content.

About File Operations

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.

Learn more about File Operations โ†’

More File Operations Examples