Skip to content

Computer Science · Ch 2 — File Handling in Python

Introduction to Files

2.1

Introduction to Files

A program’s variables exist only while the program runs. Once execution ends, the data stored in those variables is lost. This means every time you run the program, you must re-enter the input, and any output produced during the previous run is gone. For any real-world use — especially in organisations — this is impractical. An organisation needs to store employee records, inventory lists, sales data, and so on permanently, so that the same information does not have to be typed in repeatedly.

The solution is to store data on a secondary storage device (like a hard disk or SSD), where it remains even after the program stops. This is exactly what we already do with Python programs themselves: we save them in script mode with a .py extension, and each saved program is a file on the secondary device. In the same way, the data that a program reads as input and the output it generates can be saved permanently into a file.

Note

A file is a named location on a secondary storage media where data are permanently stored for later access.

The name of the file is how the operating system identifies and retrieves it. Without a name, the data would be just an anonymous block on the disk. The location refers to the path or directory where the file resides. Together, the name and location allow any program to open, read, write, or modify the data at any time — not just during the original program’s execution.

This chapter introduces the fundamental concepts of file handling in Python: what files are, why we need them, and how to work with them programmatically. The key idea is that files give data permanence and reusability, freeing us from the limitation of temporary, in-memory variables.