Abdallah Yashir Ramsing
Abdallah Yashir

Abdallah Yashir

How to create and delete a folder in Python using Pathlib?

Photo by Sincerely Media on Unsplash

How to create and delete a folder in Python using Pathlib?

This is how I use Python built-in pathlib library to efficiently create and delete folders.

Abdallah Yashir Ramsing's photo
Abdallah Yashir Ramsing
·Jan 21, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Table of contents

  • Folder Manipulation
  • Box
  • Codes

image.png

Folder Manipulation

These are the codes that I'm implementing for creating and deleting a folder.

What I like with Python for automating stuff is the language simplicity. With a few lines of code, you can do amazing things. I can also use PowerShell scripts, but I like writing cross-platform scripts or applications wherever possible.

This time I'm not using a class but calling the functions directly, as I see the case in many examples on YouTube tutorials. Perhaps that's more efficient for quick and dirty ad hoc projects.

Box

For the name, I choose Box as a synonym to file because it might be confusing. I'm already using files classes or modules from libraries such as pathlib. So this is a good way to keep things simple with the naming.

The aim is this code is to:

  • create a "posts" folder
  • place the number of transformed posts
  • zip the folder
  • delete the "posts" folder

I've yet to test the whole flow due to a lack of time.

When dealing with OS and external operations such as API calls, I like using try except in any language I'm coding with.

The reason is so that I can better track these types of errors and plan a countermeasure for them, such as retrying.

This makes the programs more resilient. On the other side, I also want in most situations that the script completely stops. For instance, if there is no Ghost JSON file in my current side project, there is no point in continuing.

Codes

box.py

from pathlib import Path

def folder_exists(folder_name):
    return Path(folder_name).is_dir()

def create_folder(folder):
    try:
        if not folder_exists(folder):
            Path(folder).mkdir(parents=True, exist_ok=True)
    except OSError as e:
        print(f"Error: {e.strerror}")

def delete_folder(folder):
    try:
        if folder_exists(folder):
            Path(folder).rmdir()
    except OSError as e:
        print(f"Error: {e.strerror}")

def sync_folder(folder):
    delete_folder(folder)
    create_folder(folder)

def zipFolder():
    return None

main.py

folder_name = "posts"
box.sync_folder(folder_name)

There are two ways of writing codes in my opinion:

  1. Typing the flow in a single function and then refactoring into relevant classes/methods/functions (if needed)
  2. creating the classes/methods/functions first (you can even write their unit tests) and then stitching everything together

In this case, I choose the second variation as it's easy to progress with the project with one quick file at a time. I also like the abstraction.

I would nevertheless recommend, especially if you're still learning the language or the programming stack, to do it as simple as possible. This is how I usually proceed when working on Java or C# for enterprise systems.

This is the whole repo.


 
Share this