📘 Python File Handling – Complete Guide with Examples


📌 1. Introduction to File Handling

File handling is a way to read, write, update, and delete files in Python. It's useful when working with logs, reports, documents, and storing data persistently.

Python has built-in functions to create, open, read, write, and close files.


📂 2. File Types in Python

We will mostly deal with text files here.


🔓 3. Opening a File

Use the built-in open() function.

file = open("example.txt", "r")

Modes:

Mode Description
"r" Read (default), file must exist
"w" Write, creates new or truncates existing file
"a" Append, adds to the end
"x" Create, fails if file exists
"b" Binary mode (e.g. "rb" or "wb")
"t" Text mode (default, used like "rt")

✅ 4. Reading from Files

read(): Read entire content