HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

12) Modules and Automation Lesson

Python Path with Python Pathlib

9 min to complete · By Martin Breuss

Python is an excellent language for writing scripts to automate tiresome and repetitive processes on your computer. One of the more exciting tasks to tackle with Python is to make it interact with your local file system.

Remember that messy Desktop?

Way too many screenshots on a Desktop

It's time that you go and clean it up. I'm serious this time: if you don't clean your Desktop now, you won't be going out tonight!

Python Pathlib Library

Python offers a couple of different ways to interact with your file system. You'll learn a module from the standard library called pathlib. You can peek into its documentation, but you'll learn about the parts you need right here in the course.

Start with Pseudocode

Start by opening up a new Python file in your IDE. Before writing any code, you'll first take a step back and think of the bigger picture, and note your tasks in pseudocode:

# Import pathlib
# Find the path to my Desktop
# List all the files on there
# Filter for screenshots only
# Create a new folder
# Move the screenshots in there

With these rough steps in mind, you're ready to start building the core functionality.

Current Working Directory

The first task you need to tackle is finding the location of your desktop on your computer and getting its absolute path. You might remember that you can do that with Bash using the pwd command after you navigate there.

Use Pathlib

How can you do the same thing using Python and pathlib? It might be a good idea to start out by figuring out where you are in the first place:

import pathlib

pathlib.Path.cwd()  # Returns the path of your current working directory

In this code snippet, you start off by importing the pathlib module from the standard library. Next, you access the Path object through the pathlib namespace and call .cwd() on it.

This will return the current working directory of your script, which will be the folder in which you saved your script.

Colorful illustration of a light bulb

Info: Because pathlib is an object-oriented module, you're scratching a couple of semi-new concepts here, namely objects and methods. You'll learn more about all of this later in the course. For now, just think of objects as things, and their methods as ways to make these things do something.

You might notice that .cwd() has a similar name to the corresponding pwd command that you can use in your terminal. Both of these commands give you the path of the folder which you are executing the command from.

Convert the Path

If you run the code you saw above in your Python REPL, then you'll see something similar to this:

PosixPath('/Users/martin/Documents/codingnomads/python-course')  # Or WindowsPath

That looks like a path, but it's also wrapped in parentheses and before the path, it says PosixPath, or WindowsPath. What's that all about?

Colorful illustration of a light bulb

Info: If you wrap the second line of code into a call to print(), then Python will show you only the path as an output:

/Users/martin/Documents/codingnomads/python-course

You'll notice that it's the same path but not wrapped inside of PosixPath or WindowsPath. The reason for this different output is that a Path object is set up in a way to print only a string representation of the path when you pass it to print(). On the other hand, if you run pathlib.Path.cwd() in the Python interpreter, then Python will show you a more complete representation of the object that the method returns.

This information about objects and different representations of them doesn't impact what you're working with. It's here for completeness in case you wonder why you'll see different outputs whether you print a Path object or run the code in the Python REPL. If it sounds confusing, then forget about it and keep moving; things will clear up along the way.

With the output in the REPL, Python is telling you that you're dealing with an object of the type pathlib.Path---this is not a string! You don't have to worry too much about what that means, however. Just remember that you're getting back more than just a string representing the path to your folder.

Convert to String

You can turn this pathlib.Path object into a str object in the same way that you converted int objects to str objects earlier on:

import pathlib

path = pathlib.Path.cwd()
str(path)

Applying str() on the pathlib.Path object will give you back just the string that represents the path to your current working directory:

'/Users/martin/Documents/codingnomads/python-course'

You can think of a call to print() doing pretty much what you did here. That's why printing a Path object gives you back just the path string without the object info around it.

If there's a tiny lightbulb turning on somewhere in the back of your head, that flickers far away and sends you some thoughts such as is everything an object in Python?, then just keep that little lightbulb flickering there for a while. You'll learn much more about objects and how they all tie together later on in this course.

For now, you'll have some fun interacting with your file system!

Summary: Python Path and Python Pathlib

  • Python's pathlib module is an excellent library for working with your computer's file system
  • pathlib.Path.cwd() returns your current working directory as aPosixPath or WindowsPath object
  • Both PosixPath and WindowsPath objects can be converted to a string with str()