Free Study Material

Introduction to File Handling

Concept

Every variable you've used so far lives only in your computer's RAM — the moment your program ends, that data is gone forever. A file is different: it's a block of information saved directly onto your computer's permanent storage (a hard disk or SSD), so it survives after the program closes, after the computer restarts, even after years.

Python treats a file almost like a physical notebook. You open it (which either creates a new notebook or finds an existing one), you write or read from it, and then you close it to make sure everything is safely saved.

Example

file = open("my_diary.txt", "w")
file.write("Hello World")
file.close()

file = open("my_diary.txt", "r")
print(file.read())
file.close()

Three steps, every time: open it, use it, close it. Forgetting the third step is one of the most common file-handling bugs — the data you wrote might never actually reach the disk. The second open-read-close here proves it did: reopening the file and printing it back shows exactly Hello World, saved on disk, not just sitting in a variable.

Note: Variables are volatile — they disappear the instant your program stops running. Files are permanent — that's the entire reason file handling exists.

Summary

Files let a program remember things beyond a single run, by storing data permanently on disk instead of temporarily in RAM. Opening, using, and closing a file is the basic three-step pattern behind everything else in this chapter.

The Problem with Variables

Imagine you solve a complex math problem on a Whiteboard. It looks great. But if the janitor comes in or the power goes out, poof! It's gone forever.

Computer Variables (RAM) are like that whiteboard. They are fast, but they are Volatile. As soon as your program ends or the computer restarts, all your data (`score = 100`) is erased.

To keep data forever, we need to write it into a Notebook. In computers, that Notebook is a File stored on the Hard Disk.

What is a File?

A file is simply a named location on a disk where data is stored permanently. It allows your program to:

Store Data

Save game scores, user lists, or settings.

Retrieve Data

Read the data back next week or next year.

Share Data

Send the file to another computer.

# -----------------------------------------------------
# CHALLENGE: Write to the Notebook
# -----------------------------------------------------
# We are going to create a permanent file.
# 
# YOUR TASK:
# 1. Change the text "Hello World" to your own name.
# 2. Run the code.
# 3. Watch for the "Success" message.

# 'w' means Write Mode (Open notebook to write)
file = open("my_diary.txt", "w")

# TODO: Write your own name inside the quotes
file.write("Hello World") 

# Always close the file to save changes!
file.close()

print("Success! File 'my_diary.txt' has been created.")

Want the full course?

Unlock all chapters, video lectures, and SQL practice exercises.

Get Full Access