Skip to content

File Manager

Medium ~25 min

What you'll build

A Python script that lists files by extension, searches for files by name pattern, and reports directory sizes — a mini file explorer.

Goals

  • Use os.listdir and os.path for file operations
  • Filter files by extension using list comprehensions
  • Calculate file sizes with os.path.getsize
  • Format a directory summary report

Prerequisites

  • File handling basics
  • Lists and list comprehensions
  • The os module

Steps

  1. 1

    List files in a directory

    Import os and define list_files(path) that returns all files in the given directory. Use os.listdir and filter to files only (not subdirectories).

    Code
    import os
    
    def list_files(path='.'):
        entries = os.listdir(path)
        files = [f for f in entries if os.path.isfile(os.path.join(path, f))]
        return sorted(files)

    Expected result

    list_files('.') returns a sorted list of file names in the current directory.

  2. 2

    Filter by extension

    Define files_by_extension(path, ext) that returns files matching the given extension. Use a list comprehension with str.endswith.

    Code
    def files_by_extension(path='.', ext='.py'):
        files = list_files(path)
        return [f for f in files if f.endswith(ext)]

    Expected result

    files_by_extension('.', '.py') returns all Python files in the current directory.

  3. 3

    Report directory sizes

    Define directory_report(path) that lists each file with its size in bytes, sorted by size (largest first). Print a formatted table.

    Code
    def directory_report(path='.'):
        files = list_files(path)
        sizes = []
        for f in files:
            full_path = os.path.join(path, f)
            size = os.path.getsize(full_path)
            sizes.append((f, size))
        sizes.sort(key=lambda x: x[1], reverse=True)
        print(f"{'File':<30} {'Size (bytes)':>15}")
        print('-' * 45)
        for name, size in sizes:
            print(f"{name:<30} {size:>15}")

    Expected result

    A formatted table of files sorted by size, largest first.

  4. 4

    Add input validation & exception handling

    Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.

    Code
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    Expected result

    Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.

  5. 5

    Write unit tests

    Write tests for the core function using unittest or assert statements, covering normal paths, boundary values, and exceptions. Tests are the safety net for code quality.

    Code
    import unittest
    
    class TestCoreFunc(unittest.TestCase):
        def test_normal(self):
            self.assertEqual(core_func(5), expected_5)
    
        def test_boundary(self):
            self.assertEqual(core_func(0), expected_0)
    
        def test_exception(self):
            with self.assertRaises(ValueError):
                core_func(-1)
    
    if __name__ == "__main__":
        unittest.main()

    Expected result

    Running python test.py prints OK with all three test cases passing.

Try it yourself

What you learned

You used the os module to interact with the filesystem, filtered with comprehensions, and formatted tabular output — skills used in build scripts, log tools, and file utilities.

Related Resources

Related Lessons

Related Practice

Related Cheatsheets

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic