Files I/O, Exceptions and Modules
File handling, exception handling, and modules are three very important parts of Python.
Almost every real project uses them. File handling helps you store and read data. Exceptions help you handle errors safely. Modules help you organize your code into smaller reusable parts.
Files in Python
Section titled “Files in Python”Files are used to store data permanently. When your program ends, variables are lost, but files keep the data saved on disk. Python can work with many types of files like text files, binary files, CSV files, logs, and more.
The basic process of working with files is:
- Open the file
- Perform operations (read/write)
- Close the file
File Modes
Section titled “File Modes”| Mode | Meaning |
|---|---|
r | Read file (must exist) |
w | Write (overwrite file) |
a | Append (add at end) |
x | Create new file |
b | Binary mode |
t | Text mode |
+ | Read and write |
Opening Files
Section titled “Opening Files”You can open a file using open() and manually close it.
file = open("notes.txt", "r", encoding="utf-8")content = file.read()print(content)file.close()Explanation:
open()opens the fileread()reads contentclose()releases the file
Problem:
If an error happens before close(), the file may remain open, which can cause bugs or memory issues.
Using with
Section titled “Using with”The with statement automatically handles closing the file, even if an error occurs.
with open("notes.txt", "r", encoding="utf-8") as file: content = file.read() print(content)Why use with:
- Automatically closes file
- Safer and cleaner
- Prevents resource leaks
Reading Files
Section titled “Reading Files”Reading means getting data from a file into your program.
Read full file
Section titled “Read full file”with open("notes.txt", "r", encoding="utf-8") as file: content = file.read()Read line by line
Section titled “Read line by line”with open("notes.txt", "r", encoding="utf-8") as file: for line in file: print(line.strip())Line-by-line reading is better for large files.
Writing and Appending
Section titled “Writing and Appending”Writing replaces the file content, while appending adds new content.
# Writewith open("notes.txt", "w", encoding="utf-8") as file: file.write("First line\n")
# Appendwith open("notes.txt", "a", encoding="utf-8") as file: file.write("Second line\n")Binary Files
Section titled “Binary Files”Binary files store data as raw bytes instead of text. These are used for images, videos, PDFs, etc.
Writing binary file
Section titled “Writing binary file”data = b"Hello"
with open("data.bin", "wb") as file: file.write(data)Reading binary file
Section titled “Reading binary file”with open("data.bin", "rb") as file: content = file.read() print(content)Object Files
Section titled “Object Files”Sometimes you want to save Python objects like lists or dictionaries directly into a file. This is called serialization.
Using pickle
Section titled “Using pickle”import pickle
data = {"name": "Sahil", "age": 21}
# Save objectwith open("data.pkl", "wb") as file: pickle.dump(data, file)
# Load objectwith open("data.pkl", "rb") as file: loaded = pickle.load(file) print(loaded)Explanation:
dump()→ store objectload()→ retrieve object
Using pathlib
Section titled “Using pathlib”pathlib is a modern way to handle file paths. It is easier and cleaner.
from pathlib import Path
path = Path("data") / "notes.txt"print(path)It works correctly on all operating systems.
Exceptions in Python
Section titled “Exceptions in Python”Exceptions are errors that occur while a program is running. Instead of crashing the program, Python allows you to handle these errors.
Common Exceptions
Section titled “Common Exceptions”| Exception | Meaning |
|---|---|
| FileNotFoundError | File not found |
| ZeroDivisionError | Division by zero |
| ValueError | Invalid value |
| TypeError | Wrong type |
| IndexError | Invalid index |
| KeyError | Missing key |
try / except / else / finally
Section titled “try / except / else / finally”try: number = int("42")except ValueError: print("Invalid number")else: print("Success:", number)finally: print("Always runs")Explanation:
try→ code that may failexcept→ runs if error occurselse→ runs if no errorfinally→ always runs
Raising Exceptions
Section titled “Raising Exceptions”You can create errors manually when something is wrong.
def set_age(age): if age < 0: raise ValueError("Age cannot be negative") return ageCustom Exceptions
Section titled “Custom Exceptions”Custom exceptions make your program more clear.
class InvalidAmountError(Exception): pass
def withdraw(balance, amount): if amount > balance: raise InvalidAmountError("Not enough balance") return balance - amountModules in Python
Section titled “Modules in Python”A module is a Python file that contains reusable code. It helps you organize your program and avoid repeating code.
Import Styles
Section titled “Import Styles”import mathimport math as mfrom math import sqrtfrom math import sqrt as square_rootCreating Your Own Module
Section titled “Creating Your Own Module”helpers.py
def clean_text(text): return text.strip().lower()main.py
from helpers import clean_text
print(clean_text(" Hello "))__name__ == __main__
Section titled “__name__ == __main__”This allows a file to act both as a script and a module.
def main(): print("Running directly")
if __name__ == "__main__": main()This block runs only when the file is executed directly.
Import Flow
Section titled “Import Flow”Packages in Python
Section titled “Packages in Python”A package is a folder that contains multiple modules. It helps organize large projects.
Example structure:
project/│├── main.py├── utils/│ ├── __init__.py│ ├── helpers.py│ └── parser.pyImporting from Packages
Section titled “Importing from Packages”from utils.helpers import clean_textRelative Imports (., ..)
Section titled “Relative Imports (., ..)”Relative imports are used inside packages to refer to files based on location.
Current directory (.)
Section titled “Current directory (.)”from .helpers import clean_textThis means: import from the same folder.
Parent directory (..)
Section titled “Parent directory (..)”from ..config import settingsThis means: go one folder up, then import.
Understanding with structure
Section titled “Understanding with structure”project/│├── app/│ ├── main.py│ └── utils/│ └── helper.pyInside helper.py:
from ..main import somethingExplanation:
..→ go to parent folder (app)- then import
main.py
Absolute vs Relative Imports
Section titled “Absolute vs Relative Imports”| Type | Example | Meaning |
|---|---|---|
| Absolute | from utils.helpers import clean_text | Full path |
| Relative | from .helpers import clean_text | Based on current file |
Absolute imports are easier to read. Relative imports are useful inside packages.