Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Programming Fundamentals · Grade 9-12

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.


Quick Answer

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. Use them whenever data must survive after the program closes: a saved game, a high-score list, a settings file, a log of sensor readings. The pattern is open, read or write, close, and the mode you open with matters: 'r' reads an existing file, 'w' creates or empties a file before writing, and 'a' adds to the end. In Python, a with block closes the file for you.

Why This Matters

Variables live in memory and vanish when a program ends, so without files a game forgets your progress and a data logger loses every reading the moment it stops. File operations let programs keep records, share data with other programs (a CSV file opened in a spreadsheet) and pick up where they left off. The mode is where damage happens: one 'w' where you meant 'a' wipes a year of saved scores.

Intuitive Explanation

A running program's variables are like writing on a whiteboard: quick, handy, and wiped when the session ends. A file is the notebook you copy the important results into before you leave. In Python, f = open('scores.txt', 'a') opens the notebook at the first blank line, f.write('Ana,95\n') adds a line (the \n marks the line break), and f.close() puts the notebook back on the shelf. Next week, open('scores.txt', 'r') and f.read() bring the same text back into memory.

Three details decide whether the data survives. The mode: 'w' empties the file the moment it opens, before you write anything, which suits a fresh save but destroys a log; 'a' keeps everything and adds to the end; 'r' fails with FileNotFoundError if the file is missing. Closing: writes are often held in a memory buffer and reach the disk only when the buffer fills or the file is closed, so a crash before close() can lose the last writes; with open(...) as f: closes automatically, even after an error. Text: a text file stores characters, so the score 95 is written as '95' and must be converted back with int() after reading.

Reading a file is a kind of input, but not every input is a file. input() waits for a person at the keyboard, and the answer is gone when the program ends; a file is already on disk and will still be there tomorrow. Choose a file when the data must outlast the run or be shared, and keyboard input when a person is answering in the moment.

Think of it like this. Files are a program's notebook, and the open mode is how you approach it: 'r' is reading without a pen, 'a' is turning to the first blank page, and 'w' is tearing out every page before you start. Closing is shutting the notebook so nothing is left half-written. Unlike torn paper, an emptied file cannot be fished out of the bin.

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.


When to Use

Use file operations when data must persist after the program ends, or come from or go to another program: save and load a game, keep a log, read a CSV of results, store settings. Choose the mode from the goal: 'r' to read, 'a' to add without losing anything, 'w' only when replacing the whole file is intended. If the data is needed only while the program runs, keep it in variables or a list. If a person is typing answers right now, that is ordinary input, not a file.

Tip. Ask: Must the data survive after the program ends, or come from or go to a file on disk?

How to Recognize It

Decide where the data lives before and after the program runs, and what must happen to anything already in the file.

  1. Must the data still exist the next time the program starts, like a saved game or a high-score table?

    Yes means write it to a file. If it is only needed while the program runs, keep it in a Variable or a list in memory.

  2. Does the file already hold data that must be kept?

    Yes means open it with 'a' to add to the end, or read it first and write everything back. Opening with 'w' empties the file the moment it opens.

  3. Does the data come from the keyboard or go to the screen rather than to disk?

    Yes means it is ordinary Input/Output with input() and print(), and nothing is saved once the program stops.

  4. Could the file be missing, empty, or laid out differently than expected?

    Yes means handle that case: catch FileNotFoundError, and convert each line yourself, because reading a text file always gives strings, even for a line that says 95.

File Operations vs Input/Output vs Variable vs Storage

Reading a file, typing at the keyboard, keeping a value in memory and the disk itself all involve data going in and out. Ask whether the data must outlive the program, and whether you mean the code that moves it or the hardware that holds it.

File Operations

Meaning
File operations are the steps a program uses to open, read, write and close files so that data lasts between runs.
Key test
Data goes to or comes from a named file on disk and survives restarts.
Example
Opening save.txt with mode 'a' and writing 'level 4' adds a line that is still there tomorrow.

Input/Output

Meaning
Input/output is how a program takes data in and sends results out, most often from a keyboard and to a screen.
Key test
A person types or reads it; nothing is kept after the program ends.
Example
name = input('Name? ') then print('Hi', name); close the program and the name is gone.

Variable

Meaning
A variable holds a value in the computer's memory only while the program is running.
Key test
Lives in memory and is lost when the program closes or crashes.
Example
high_score = 900 goes back to its starting value every time the game restarts.

Storage

Meaning
Storage is the hardware, such as an SSD or a hard drive, that keeps data when the power is off.
Key test
The physical device, not the code that reads or writes it.
Example
A 512 GB SSD holds the saved files that file operations create and read.

Formula & Notation

Worked Examples

Example 1 — Append a score and read the file back

Easy

scores.txt holds two lines, Ana,95 and Ben,88, each ending with a line break. A program runs with open('scores.txt', 'a') as f: f.write('Cy,91\n'). Later, another program reads the file line by line, splits each line at the comma and adds up the scores. What does the file contain, and what total is computed?
Show the steps and the answer
  1. Mode 'a' keeps the two existing lines and writes Cy,91 after them.

    Append mode starts writing at the end of the file and erases nothing.

  2. When the with block ends, the file is closed, so all three lines are on disk.

    Closing flushes anything still waiting in memory, and the with block does it automatically.

  3. Split each line at the comma: Ana,95 gives '95', Ben,88 gives '88', Cy,91 gives '91'.

    Everything read from a text file is a string, so the score parts are text until converted.

  4. Convert and add: int('95') + int('88') + int('91') = 95 + 88 + 91 = 274.

    Adding the strings without converting would join them into '958891' instead of summing them.

Answer: The file holds three lines (Ana,95; Ben,88; Cy,91), and the total is 274.

Takeaway: Use 'a' to add to a file without losing what is there, and convert text read from a file before doing arithmetic with it.

Example 2 — The first run, before the file exists

Standard

A game loads its best score at startup with best = int(open('best.txt', 'r').read()). On a brand-new computer, best.txt does not exist yet. What happens, and how should the game start with best = 0 and keep a new best of 1250 for next time?
Show the steps and the answer
  1. Opening a missing file in 'r' mode raises FileNotFoundError, and the game stops.

    Unlike 'w' and 'a', read mode never creates a file.

  2. Wrap the read: try: with open('best.txt', 'r') as f: best = int(f.read()), and except FileNotFoundError: best = 0.

    The except branch runs only when the file is missing, giving a sensible starting value.

  3. When the game ends with a new best of 1250, write it with open('best.txt', 'w') and f.write(str(1250)).

    Here 'w' is the right mode: the file holds one value that should be replaced, and str() turns the number into text.

  4. Next startup: the file exists and holds '1250', so best = int('1250') = 1250.

    The value has survived between runs, which is the whole reason for using a file.

Answer: Without handling, the game crashes with FileNotFoundError. With try/except it starts at best = 0, saves 1250 with mode 'w', and loads 1250 on the next run.

Takeaway: Reading assumes the file exists, so plan for the first run; choose 'w' only when the whole file should be replaced.

Example 3 — Find the mistake: a log that keeps one line

Application

A science club logs one temperature reading per hour. Each hour, Nia's program runs with open('log.txt', 'w') as f: f.write(str(reading) + '\n'). After 24 hours the file holds only one line. Find the mistake and correct it.
Show the steps and the answer
  1. Look at the mode: 'w' empties log.txt every time it is opened.

    Write mode cuts the file to zero length before the first write, so each hour erases the hours before it.

  2. Trace the first three hours: each run opens an empty file and leaves exactly one line.

    Because every run starts from nothing, the line count never grows past one.

  3. Fix: open('log.txt', 'a') instead.

    Append mode adds the new line after the existing ones, and it creates the file on the first run if it is missing.

  4. Check: after 24 runs in 'a' mode the file holds 24 lines, one per hour.

    Each run adds exactly one line and removes none.

Answer: Open the file with mode 'a' instead of 'w'. After 24 hours the log then holds 24 lines.

Takeaway: 'w' means replace the whole file and 'a' means add to the end; a log or history always needs 'a'.

Where You'll See It

  • Saving your game

    When you hit 'Save', the game writes your progress to a file so it's still there after you close it; loading reads that file back — without files, all progress would vanish when the program ends.

  • A high-score list

    A game appends each new high score to a file with mode 'a' so old scores stay; opening with 'w' instead would erase the whole list and start blank.

  • Reading a settings file

    An app opens its config file on startup to read your preferences; if that file is missing it must handle the error instead of crashing with FileNotFoundError.

Common Mistakes

  1. The slip: Opening a file in 'w' (write) mode adds to what's already there.

    Why it's tempting: 'Write' sounds like 'write some more', as if you're adding to the page.

    Instead: 'w' truncates the file to empty before writing, erasing existing content. Use 'a' (append) to add to the end without deleting.

  2. The slip: You don't really need to close a file; the program ends eventually anyway.

    Why it's tempting: The data seems written the moment you call write, so closing feels optional.

    Instead: Writes may be buffered and not saved until close (or the file stays locked). Always close, or use a with-block that closes automatically.

  3. The slip: Opening a file for reading will create it if it isn't there.

    Why it's tempting: Opening for writing does create the file, so reading seems like it would too.

    Instead: Opening a missing file in read mode raises FileNotFoundError; check that the file exists or handle the error before reading.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. log.txt starts empty. A program runs 5 times, and each run opens log.txt in 'a' mode and writes one line, 'run'. How many lines are in the file? What if it used 'w' instead?

    Hint: Append adds to the end; write mode clears the file first.

  2. scores.txt has three lines: 90, 75, 82. The code reads them with f.readlines() and adds int(line) for each line. What is the total?

    Hint: int() ignores the newline at the end of each line.

  3. fruit.txt has the lines apple, banana, cherry. The code calls f.readline() twice, then f.read(). What does the f.read() call return?

    Hint: Reading moves a position forward through the file.

  4. On the first run, settings.txt does not exist yet. What should the program do so it does not crash with a FileNotFoundError?

    Hint: Think about catching the error and what a sensible starting point is.

  5. Program A asks the user to type their name and prints a greeting. Program B saves the high score so it is still there tomorrow. Which needs file operations?

    Hint: Which data must survive after the program closes?

  6. A student writes f = open('data.txt', 'w') then f.write('results') and never closes the file, saying: 'The data is saved the moment write runs.' What is wrong?

    Hint: Where does written data wait before it reaches the disk?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

What is the difference between a text file and a binary file?

A text file stores characters, so a plain editor shows readable lines and Python's read() gives you strings. A binary file, such as a PNG image or an MP3, stores raw bytes that only make sense to a program that knows the format; opened with mode 'rb', read() gives bytes instead. Opening an image as text usually fails or shows nonsense, because its bytes were never meant as characters.

Why does my file not appear where I expected?

A file name with no folder, like 'scores.txt', is a relative path: it is looked up in the current working directory, which is wherever the program was started from, not always the folder that holds your code. Run the same script from somewhere else and it creates or reads a different file. Printing os.getcwd() shows the folder in use, and a full path such as C:/games/scores.txt removes the doubt.

Why are CSV files so common for saving data?

CSV, short for comma-separated values, stores a table as plain text: one row per line, with commas between the columns, like Ana,40. Any spreadsheet can open it and any language can read it, which makes it a common way to pass data between programs. The catch is that everything comes back as text, and a value that itself contains a comma must be wrapped in quotes, so Python's csv module is safer than splitting lines by hand.

Learning Path

← Before

Input/Output
File Operations

You are here

Next →

Nothing after this yet
You need Input/Output (how a program takes data in and sends results out) first. File operations add storage that outlasts a single run: opening with the right mode, reading or writing text, and closing safely. With them you can build programs that keep high scores, log experiment data to a CSV for a spreadsheet, load settings at startup, and process data sets far too large to type in by hand.

See Also