10 Examples to Master Python Pathlib | by Soner Yıldırım | Towards Data Science

The pathlib module of Python makes it very easy and efficient to deal with file paths.
The os.path module can also be used to handle path name operations. The difference is that path module creates strings that represent file paths whereas pathlib creates a path object.
One important advantage of using path objects instead of a string is that we can call methods on a path object. Pathlib module provides many useful methods as we will see in the examples.
In this article, we will go through 10 examples to master how to use the pathlib module.
Let’s start with importing pathlib and create a path object.
import pathlibpathlib.Path()PosixPath('.') #relative path to the current folder
If we call the Path method with no arguments, it will create a relative path to the folder we are currently working in. The paths can be described as relative or absolute.
Relative path: The path relative to the folder we are currently working in.
Absolute path: The path that is relative to the operating system
In order to make the distinction more clear, I will also create the absolute path to the folder I’m currently working in:
PosixPath('.') #relative pathPosixPath('/home/soner/Desktop/data') #absolute path
We can call the path method by passing the folder and file names as separate strings. I’m currently running the examples on a jupyter notebook which is saved in a folder named “data”. There is a “names” folder in the “data” folder and inside the “names”, I have a file called “file1.json”.
I will create a path object that represents the relative path to this file.
p = pathlib.Path("names", "file1.json")pPosixPath('names/file1.json')
In some cases, we may need to use the absolute path instead of the relative path. The resolve method is used to convert a relative path to an absolute path.
We can call it on the path object we previously created.
p.resolve()PosixPath('/home/soner/Desktop/data/names/file1.json')
The returned path is the absolute path of file1. Another way to convert a relative path to an absolute path is through the absolute method.
p.absolute()PosixPath('/home/soner/Desktop/data/names/file1.json')
The pathlib module has a method that can be used to read the text inside the file.
p.read_text()'{\n    "John": 1,\n    "Jane": 2\n}'
We can see the content of file1.json but the format is not nice and clean. The json module can be used together with the pathlib to make things better.
import jsonjson.loads(p.read_text()){'John': 1, 'Jane': 2}
We can create a path that is relative to another path.
p1 = pathlib.Path("names", "file1.json")p2 = pathlib.Path("names")p_relative = p1.relative_to(p2)p_relativePosixPath('file1.json')
The p_relative is the relative path of p2 (names folder) to p1 (file1 inside the names folder). It can also be considered as an absolute path based on another path (not the operating system).
We can use the samefile method to compare if two paths represent the same files. The paths can be relative or absolute.
Consider the following two paths.
p1 = pathlib.Path("names", "file1.json")p2 = p1.resolve()
The p2 is the absolute path version of the p1. Let’s compare them using the samefile method.
p1.samefile(p2)True
We can check if a path represents a file or a directory. The methods are, not surprisingly, is_file and is_dir.
p1.is_dir()Falsep1.is_file()True
The path p1 represents a json file so is_file returns True.
The pathlib module can also be used to move files.
I have file1.json stores in the data folder.
p = pathlib.Path("names", "file1.json")
I want to move file1 into the id folder and rename it as file1-a. The rename method is used as follows.
p.rename(pathlib.Path("id", "file1-a.json"))
The file1 does not exist in data folder anymore. We can check it using the exists method.
pPosixPath('names/file1.json')p.exists()False
The pathlib module provides a way to create a new file and write text to it.
Let’s create a text to write to the path object.
p = pathlib.Path("id", "file1-a.json")d = json.loads(p.read_text())d{'John': 1, 'Jane': 2}
We can now create a path and call the write_text method on it.
text = json.dumps(d)pathlib.Path("id", "newfile.json").write_text(text)
The dumps method of json module converts the content of the json file to text. We pass this text to the write_text method and it is written in the newfile.json.
We can confirm it by reading the content of the newfile.json.
pathlib.Path("id", "newfile.json").read_text()'{"John": 1, "Jane": 2}'
The folder structure is hierarchical so the parent folder is one level above. We can call the parent or parents methods on paths.
The parent method will return the path that represents one level above.
pPosixPath('/home/soner/Desktop/data/names/file1.json')p.parentPosixPath('/home/soner/Desktop/data/names')
The parents return a sequence of all the parent folders.
list(p.parents)[PosixPath('/home/soner/Desktop/data/names'), PosixPath('/home/soner/Desktop/data'), PosixPath('/home/soner/Desktop'), PosixPath('/home/soner'), PosixPath('/home'), PosixPath('/')]
The pathlib module provides convenient and robust ways to deal with file paths. Pathlib creates the paths as objects so it is more preferred than the os.path module. The os.path creates paths as strings.
We have covered the most commonly used methods of the pathlib. However, there is more to it. If you’d like to read further, you can always visit the official documentation.
Thank you for reading. Please let me know if you have any feedback.