⇦ Back

1 Set Up

Import the Python packages you will need:

import os
from pathlib import Path

Both of these come pre-packaged with Python so you won’t need to install anything.

Next, create a whole bunch of toy folders and files that we can use for this tutorial:

# Create directories
Path('Folder 1', 'Folder 1.1').mkdir(parents=True, exist_ok=True)
Path('Folder 1', 'Folder 1.2').mkdir(parents=True, exist_ok=True)
Path('Folder 2', 'Folder 2.1').mkdir(parents=True, exist_ok=True)
Path('Folder 2', 'Folder 2.2').mkdir(parents=True, exist_ok=True)
Path('Folder 3', 'Folder 3.1').mkdir(parents=True, exist_ok=True)
Path('Folder 3', 'Folder 3.2').mkdir(parents=True, exist_ok=True)

# Create files
paths = [
    Path('Example File 1.txt'),
    Path('Folder 1', 'Example File 1.1.txt'),
    Path('Folder 1', 'Folder 1.1', 'Example File 1.1.1.txt'),
    Path('Folder 1', 'Folder 1.1', 'Example File 1.1.2.txt'),
    Path('Folder 2', 'Example File 2.1.txt'),
    Path('Folder 2', 'Folder 2.2', 'Example File 2.2.1.txt'),
    Path('Folder 2', 'Folder 2.2', 'Example File 2.2.2.txt'),
    Path('Folder 3', 'Example File 3.1.txt'),
]
for path in paths:
    # Open file in 'write' mode, erasing content if the file exists
    f = open(path, 'w')
    # Write to a file
    f.write('Hi, mom')
    # Close the file
    f.close()

6 Tear Down

Let’s clean up after ourselves: delete the toy files that we created for this example script:

# Delete files
paths = [
    Path('Example File 1.txt'),
    Path('Folder 1', 'Example File 1.1.txt'),
    Path('Folder 1', 'Folder 1.1', 'Example File 1.1.1.txt'),
    Path('Folder 1', 'Folder 1.1', 'Example File 1.1.2.txt'),
    Path('Folder 2', 'Example File 2.1.txt'),
    Path('Folder 2', 'Folder 2.2', 'Example File 2.2.1.txt'),
    Path('Folder 2', 'Folder 2.2', 'Example File 2.2.2.txt'),
    Path('Folder 3', 'Example File 3.1.txt'),
]
for path in paths:
    path.unlink()

Once all the folders are empty we can delete them as well:

# Delete directories
Path('Folder 1', 'Folder 1.1').rmdir()
Path('Folder 1', 'Folder 1.2').rmdir()
Path('Folder 2', 'Folder 2.1').rmdir()
Path('Folder 2', 'Folder 2.2').rmdir()
Path('Folder 3', 'Folder 3.1').rmdir()
Path('Folder 3', 'Folder 3.2').rmdir()
Path('Folder 1').rmdir()
Path('Folder 2').rmdir()
Path('Folder 3').rmdir()

⇦ Back