Directories in Python

Here’s the translated Python code and explanation in Markdown format suitable for Hugo:

Our first program will demonstrate working with directories in Python. Here’s the full source code:

import os
import shutil

def check(e):
    if e:
        raise e

def main():
    # Create a new sub-directory in the current working directory
    os.mkdir("subdir")

    # When creating temporary directories, it's good practice to use a context manager
    # for automatic cleanup. We'll simulate this behavior with a try-finally block.
    try:
        # Helper function to create a new empty file
        def create_empty_file(name):
            with open(name, 'w'):
                pass

        create_empty_file("subdir/file1")

        # We can create a hierarchy of directories, including parents
        # This is similar to the command-line `mkdir -p`
        os.makedirs("subdir/parent/child")

        create_empty_file("subdir/parent/file2")
        create_empty_file("subdir/parent/file3")
        create_empty_file("subdir/parent/child/file4")

        # os.listdir lists directory contents
        print("Listing subdir/parent")
        for entry in os.listdir("subdir/parent"):
            path = os.path.join("subdir/parent", entry)
            print(" ", entry, os.path.isdir(path))

        # os.chdir lets us change the current working directory
        os.chdir("subdir/parent/child")

        # Now we'll see the contents of subdir/parent/child when listing the current directory
        print("Listing subdir/parent/child")
        for entry in os.listdir():
            print(" ", entry, os.path.isdir(entry))

        # Change back to where we started
        os.chdir("../../..")

        # We can also visit a directory recursively, including all its sub-directories
        print("Visiting subdir")
        for root, dirs, files in os.walk("subdir"):
            for name in dirs + files:
                path = os.path.join(root, name)
                print(" ", path, os.path.isdir(path))

    finally:
        # Clean up: remove the entire directory tree
        shutil.rmtree("subdir")

if __name__ == "__main__":
    main()

To run the program, save it as directories.py and use python:

$ python directories.py
Listing subdir/parent
  child True
  file2 False
  file3 False
Listing subdir/parent/child
  file4 False
Visiting subdir
  subdir True
  subdir/file1 False
  subdir/parent True
  subdir/parent/child True
  subdir/parent/file2 False
  subdir/parent/file3 False
  subdir/parent/child/file4 False

This program demonstrates various operations with directories in Python:

  1. We use os.mkdir() to create a single directory and os.makedirs() to create a directory hierarchy.
  2. The create_empty_file() function demonstrates creating empty files.
  3. We use os.listdir() to list directory contents and os.path.isdir() to check if an entry is a directory.
  4. os.chdir() is used to change the current working directory.
  5. os.walk() is used to recursively visit all files and directories in a directory tree.
  6. We use a try-finally block to ensure cleanup (shutil.rmtree()) even if an exception occurs.

Note that Python’s os and shutil modules provide a platform-independent way to work with directories and files, similar to the functionality demonstrated in the original example.