Skip to main content

Module 14: 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, and binary files.
  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 using w and a modes.
  4. Safe File Opening (with open): Using the with statement to ensure files are closed automatically and safely.