File Handling

Applied Python · free study notes · Updated

File Handling in Python

Course: Coding & Web Development
Subject: Python
Topic: File Handling


1. Simple Explanation

File handling is the process of opening, reading, writing, updating, and closing files in a program.
Python offers a built‑in module io (accessed via the open() function) that lets you work with text and binary files easily.


2. Key Points

Concept What it is Typical usage Example
open() Returns a file object. f = open('file.txt', 'r')
File modes Define how the file is accessed. 'r' read, 'w' write (truncate), 'a' append, 'b' binary, '+' read/write open('data.bin', 'rb+')
Context manager (with) Automatically closes the file, even on errors. with open('file.txt') as f:
Reading f.read(), f.readline(), f.readlines() Get entire file, one line, or list of lines
Writing f.write(), f.writelines() Add content to file
Seeking f.seek(offset, whence) Move pointer in file
File attributes f.name, f.mode, f.closed Inspect file state
Binary vs Text Text files use encoding (utf-8). Binary files read/write bytes. Use 'b' mode for images, audio, etc.
Error handling FileNotFoundError, IOError Use try/except
Path handling os.path, pathlib Cross‑platform paths

3. Worked Example

We’ll create a small script that:

  1. Creates a text file students.txt.
  2. Writes several names.
  3. Reads the file line by line.
  4. Appends a new name.
  5. Prints the final content.
# students.py
from pathlib import Path

file_path = Path('students.txt')

# 1. Write initial names (overwrite if file exists)
names = ['Alice', 'Bob', 'Charlie']
with file_path.open('w', encoding='utf-8') as f:
    for name in names:
        f.write(name + '\n')

# 2. Read and print the file
print('--- Initial file contents ---')
with file_path.open('r', encoding='utf-8') as f:
    for line in f:
        print(line.strip())

# 3. Append a new name
with file_path.open('a', encoding='utf-8') as f:
    f.write('Diana\n')

# 4. Read again to verify
print('\n--- After appending Diana ---')
with file_path.open('r', encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        print(line.strip())

# 5. Clean up (optional)
# file_path.unlink()  # Deletes the file

Output

--- Initial file contents ---
Alice
Bob
Charlie

--- After appending Diana ---
Alice
Bob
Charlie
Diana

Explanation

  • Path('students.txt') creates a Path object; works on Windows, macOS, Linux.
  • open('w') truncates/creates file and writes three names, each followed by a newline.
  • Reading with for line in f: iterates over lines lazily.
  • open('a') opens the file for appending; new content is added at the end.
  • readlines() returns a list of all lines.

4. Quick Revision Summary

Topic What to remember
Opening a file open(file, mode, encoding) – use with to auto‑close.
Modes r, w, a, b, + – combine as needed.
Reading read(), readline(), readlines() – choose based on size.
Writing write(), writelines() – always add newline if necessary.
Appending Use 'a' mode; pointer stays at end.
Binary files No encoding; read/write bytes.
Error handling Catch FileNotFoundError, IOError.
Path operations Prefer pathlib.Path over string paths.
Best practice Use context managers (with) to avoid leaks.

Practice Tip
Create a script that reads a CSV file, counts the number of rows, and writes the count to a new file. This will reinforce opening, reading, writing, and path handling.

Your note

Page 1

Doubt hai is topic me?

Free AI teacher se poocho — 24/7, step by step.