Skip to main content

Module 15: File Handling

In most programs we write, the data stored in variables or lists is lost once the program is closed or the computer is turned off because it is kept in temporary memory (RAM).

To keep the data permanently for future use, we must store it in files on the hard disk. Creating, reading, and writing files using Python is called File Handling.


Real-world Analogy

Think of a physical file cabinet in an office.

  • When you need information, you pull a file out of the cabinet and read it (Reading).
  • When you have new information, you write it down and store it in a file (Writing).
  • If you want to add more notes to an existing file, you add them to the end of the document (Appending).

In Python, we perform these exact actions programmatically.


Importance in Data Science and AI

In Data Science, the data we analyze is almost always stored in external files such as text files (.txt), CSV files (.csv), or Excel spreadsheets.

  • Loading customer records from a CSV file to analyze them.
  • Saving the final output or performance metrics of a machine learning model to a text file.
  • Understanding file handling is fundamental for dealing with real-world datasets.

What we will learn in this module:

In this module, we will learn:

  1. What is a File?: Introduction to files, text files vs binary files, and file modes.
  2. Reading Files: How to read file contents using read(), readline(), and readlines().
  3. Writing & Appending: How to write data to new files and append to existing files.
  4. Handling File Errors: Using try-except and os.path.exists() for safe file operations.
  5. CSV Basics: Reading and writing CSV files using Python's csv module.

Quick Summary

  • Persistent Storage: File handling allows programs to read external datasets and save computation results permanently to disk.
  • File Types: Text files (human-readable characters) vs. Binary files (raw bytes like images and audio).
  • Safe Management: The modern with open(...) as f: syntax guarantees files are closed cleanly automatically.

What's Next?

Let's start by learning what files are and the different access modes in the next lesson!