What is the Pathlib module in Python?

The pathlib module uses an object-oriented approach to deal with the filesystem in a platform-agnostic and intuitive manner. The module was first introduced in Python 3.4.

Here, we will learn how to use the pathlib module with examples.

Examples

1. Construct a path object given a path string

A path object can be created by passing the path string as a parameter while in object creation:

new_path = Path("/users/john/Docs")

2. Check if the given path exists

new_path.exists()

3. Get the name of the file in the path

new_path = Path("/usr/abhi/Docs/hello.py")
print(new_path.name)

4. Get the extension of the file

new_path = Path("kib.yaml")
print(new_path.suffix)

If there is more than one extension, then use .suffixes:

new_path = Path("file.tar.gz")
print(new_path.suffixes)

5. Get the parent/ancestor directories of a given path

new_path = Path("/Users/abhi/Downloads/MatterHorn/documentation/img/top_no_dm.gif")
print(new_path.parent)

To get all the ancestors, use .parents:

print(list(new_path.parents))

6. Check if the given path is a directory or file

print(new_path.is_file())
# OR
print(new_path.is_dir())

7. Get the statistics of the file path

new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(new_path.stat())

8. Get the current working directory

print(Path.cwd())

9. List all the files in the current working directory matching a pattern

new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(list(new_path.glob("*.gif")))

10. Create a file in the path along with the parent directory if needed

new_path = Path("/Users/abhi/Downloads/dir1/dir2/hello_world.py")
new_path.mkdir(parents=True)

11. List all files in the current directory

new_path = Path("/Users/abhi/Downloads/UMatter/documentation/img")
print(list(new_path.iterdir()))

12. Join two paths

path1 = Path("/Users/abhi/Downloads")
path2 = Path("dir1/dir2/hello_world.py")
print(path1.joinpath(path2))

13. Given the relative path, get the absolute path of the file

new_path = Path("hello_world.py")
print(new_path.absolute())

14. Read text from the given path

new_path = Path("/Users/abhi/Downloads/dir1/dir2/a.txt")
print(new_path.read_text())

15. Write text to the given path

new_path = Path("/Users/abhi/Downloads/dir1/dir2/b.txt")
new_path.write_text("hello educative")

Free Resources