File Handling in Python: A Practical Guide

File Operations in Python

Objective

This exercise demonstrates fundamental file handling techniques using Python's built-in modules and standard libraries.

Task Descriptions

1. Listing Directory Contents

Create a script that prompts the user for a directory path and displays all items within it.

import os

directory = input("Enter directory path: ")
try:
    contents = os.listdir(directory)
    print("Contents of the directory:")
    for item in contents:
        print(item)
except FileNotFoundError:
    print("Directory not found.")

2. Filtering and Copying Files by Extension

Develop a program that accepts a directory and file extension from the user, then copies all matching files to a new location.

import os
import shutil

dir_path = input("Enter directory path: ")
extension = input("Enter file extension (e.g., .txt): ")
target_dir = r"D:\copied_files"

os.makedirs(target_dir, exist_ok=True)

for filename in os.listdir(dir_path):
    if filename.endswith(extention):
        source_file = os.path.join(dir_path, filename)
        destination_file = os.path.join(target_dir, filename)
        shutil.copy(source_file, destination_file)
        print(f"Copied: {filename}")

print("All matching files have been copied.")

3. Recursive Size Calculation

Write a program that calculates the total size of all files in a given directory and its subdirectroies.

import os

total_size = 0
path = input("Enter directory path to calculate size: ")

for root, dirs, files in os.walk(path):
    for file in files:
        file_path = os.path.join(root, file)
        try:
            total_size += os.path.getsize(file_path)
        except OSError:
            continue

print(f"Total size: {total_size} bytes")

4. Searching for Keywords in Filenames

Construct a utility that searches for a keyword in filenames within a specified directory tree.

import os

search_path = input("Enter directory path: ")
keyword = input("Enter search keyword: ")
matching_files = []

for root, dirs, files in os.walk(search_path):
    for file in files:
        if keyword in file:
            full_path = os.path.join(root, file)
            matching_files.append(full_path)

if matching_files:
    print("Files containing the keyword:")
    for file in matching_files:
        print(file)
else:
    print("No files found with the specified keyword.")

Key Concepts Covered

  • Utilizing os.listdir() for listing directory contents.
  • Employing os.walk() to traverse directories recursively.
  • Using os.path.join() for constructing file paths correctly.
  • Applying os.path.getsize() to retrieve file sizes.
  • Leveraging shutil.copy() for file dupliaction.
  • Filtering files based on extensions and keywords.

Common Challenges

  1. Understanding os.walk(): This function yields tuples of (root, dirs, files), which can be confusing at first.
  2. File Extension Matching: The .endswith() method effective filters files by their extension.
  3. Size Calculation Errors: Ensuring correct path arguments to os.path.getsize() avoids runtime errors.

Learning Outcomes

Through hands-on practice, students gain proficiency in Python's file I/O capabilities and learn how to manipulate filesystem structures programmatically.

Tags: python File Handling os module shutil module Directory Traversal

Posted on Wed, 19 Aug 2026 16:45:16 +0000 by headsmack