How to Use Python pathlib Module

Contents
In this article, you will learn how to use Python pathlib module.
Python pathlib Module
Python’s pathlib module provides an object-oriented interface for working with file system paths. It allows you to perform common operations like creating, reading, and modifying files and directories with a simplified syntax. Here’s how to use it:
Importing the pathlib module
You can import the pathlib module like this:
from pathlib import Path
Creating a Path object
To create a Path object, you can pass a path string to the Path constructor. For example, to create a Path object for the current working directory, you can use:
path = Path('.')
You can also create a Path object for a specific file or directory by passing its path to the constructor. For example, to create a Path object for a file named example.txt in the current directory, you can use:
path = Path('example.txt')
Checking if a Path exists
To check if a path exists, you can use the exists() method of a Path object. For example, to check if a file named example.txt exists in the current directory, you can use:
path = Path('example.txt')
if path.exists():
print('File exists')
else:
print('File does not exist')
Creating a new file
To create a new file, you can use the touch() method of a Path object. For example, to create a file named example.txt in the current directory, you can use:
path = Path('example.txt')
path.touch()
Creating a new directory
To create a new directory, you can use the mkdir() method of a Path object. For example, to create a directory named example_dir in the current directory, you can use:
path = Path('example_dir')
path.mkdir()
Listing contents of a directory
To list the contents of a directory, you can use the iterdir() method of a Path object. For example, to list the contents of the current directory, you can use:
path = Path('.')
for item in path.iterdir():
print(item)
Getting the file name and extension
To get the file name and extension of a file, you can use the name and suffix properties of a Path object, respectively. For example, to get the file name and extension of a file named example.txt, you can use:
path = Path('example.txt')
print(path.name) # prints 'example.txt'
print(path.suffix) # prints '.txt'
Joining paths
To join two paths, you can use the / operator on Path objects. For example, to join the current directory and a file named example.txt, you can use:
path = Path('.') / 'example.txt'
Reading from a file
To read the contents of a file, you can use the read_text() method of a Path object. For example, to read the contents of a file named example.txt, you can use:
path = Path('example.txt')
contents = path.read_text()
print(contents)
Writing to a file
To write contents to a file, you can use the write_text() method of a Path object. For example, to write the string “Hello, world!” to a file named example.txt, you can use:
path = Path('example.txt')
path.write_text('Hello, world!')