The pathlib module in the Python standard library is no doubt powerful - maybe more powerful than what I was ready for. And this showed as I first worked with pathlib on several labs and projects focused on printing file names in the terminal, changing file names, and moving files. But working with pathlib on the aforementioned tasks helped to become more comfortable with it's functionality. One specific, and rather brief script, I completed with pathlib was a file mover.
My file mover script utilized pathlib (import pathlib) to create a Path object and assign it to a variable (folder = pathlib.Path(some directory). In my project, "some directory" is a directory for a specific folder on my computer. I then created a new Path object, assigned it to the variable "new_path", where I intended to move specific files to (new_path = pathlib.Path(some directory/screenshots). Additionally, using the .mkdir() method, if "some directory/screenshots" did not already exist, it will get created (new_path.mkdir(exist_ok=True)). The "exist_ok=True" argument here is necessary to avoid a "FileExistsError" if the directory already exists.
The next block of my code utilizes a for loop to iterate through each file within the directory defined by the variable "folder" (for filepath in folder.iterdir():). A conditional statement is then nested in the for loop to identify the file type I am interested in moving. This line of code uses the ".suffix" attribute to find files with a specific extension. In this project, I identify screenshots with the ".png" extension (if filepath.suffix == ".png"). If the if statement evaluates as True, meaning the file is indeed a screenshot, the script uses the ".joinpath()" method to create a new destination path into the "some directory/screenshots" where the .png-containing file gets stored. This new destination path was stored in the variable "new_filepath" (new_filepath = new_path.joinpath(filepath.name)). Lastly, the .replace() method is used on filepath to perform the actual move of the ".png" file to the new directory (filepath.replace(new_filepath)).
This project was a great example of the automation that can be achieved with Python. As I become more familiar with using the pathlib module, I am sure I will find new uses for it that will simplify the more mundane tasks I perform on my computer.
Top comments (0)