Python Path

Summary: in this tutorial, you’ll learn how to use the Python Path class from the pathlib module to interact with the file system across platforms easily and effectively.

Introduction to the Python Path class

The pathlib is a built-in module that allows you to interact with the file system more effectively. In addition, the pathlib works accross operating systems including Windows, macOS and Linux.

The pathlib treats the paths as objects. So instead of using paths as strings, you use the Path class to manage paths.

To use the Path class from the pathlib module, you import it as follows:

from pathlib import PathCode language: Python (python)

Getting the path of the home directory

Since Path is a class, you can access its methods and properies. For example, you can get the path of the home directory by calling the home() static method like this:

from pathlib import Path

home = Path.home()
print(home)Code language: Python (python)

On Windows, it returns something like:

C:\Users\rootCode language: Python (python)

On Linux, it returns the home directory of the current user:

/home/rootCode language: Python (python)

…with an assumption that the root is the user on both Windows and Linux.

Getting the path of the current working directory

Similarly, you can call the cwd() static method to get the path of the current working directory:

from pathlib import Path

cwd = Path.cwd()
print(cwd)Code language: Python (python)

Output:

D:\demo\pathlibCode language: Python (python)

Creating a Path object from a string

To create a Path object, you can pass a string to the Path() like this:

from pathlib import Path

path = Path('readme.txt')Code language: Python (python)

Getting the parent directory of a path

To get the first parent directory path of the current working directory by accessing the parent property like this:

from pathlib import Path

path = Path('D:/home/root/projects/project_a/tests')
print(path.parent)Code language: Python (python)

Output:

D:\home\root\projects\project_aCode language: Python (python)

To get the path of the nth parent directory, you can use the parents property:

from pathlib import Path

path = Path('D:/home/root/projects/project_a/tests')
print(path.parents[3])Code language: Python (python)

Output:

D:\homeCode language: Python (python)

Joining paths

To join paths, you use the / operator. For example, the get the path of the Downloads directory located inside the home directory, you can use the / operator as follows:

from pathlib import Path

path = Path.home() / 'Downloads'
print(path)Code language: Python (python)

Output:

C:\Users\root\DownloadsCode language: Python (python)

The / operator returns a new Path object. Therefore, you can use it multiple times in an expression. For example:

from pathlib import Path

path = Path.home() / 'Downloads' / 'Documents'
print(path)Code language: Python (python)

Output:

C:\Users\root\Downloads\DocumentsCode language: Python (python)

Checking if a path exists

A path can be a file or a directory, to check if a path exists, you can use the exists() method. For example:

from pathlib import Path

path = Path('readme.txt')
print(path.exists())Code language: Python (python)

The exists() method returns True if the path exists or False otherwise.

Resolving a path

To get the full path of a Path object, you use the resolve() method. For example:

from pathlib import Path

path = Path('readme.txt')
full_path = path.resolve()

print(full_path)Code language: Python (python)

Output:

D:\demo\path\readme.txtCode language: Python (python)

Getting file name and extension

To get the file name of a path, you use the name property:

from pathlib import Path

path = Path('readme.txt')
print(path.name)Code language: Python (python)

Output:

readme.txtCode language: Python (python)

To get the file name without extension, you use the stem property:

from pathlib import Path

path = Path('readme.txt')

print(path.stem)Code language: Python (python)

Output:

readmeCode language: Python (python)

To get the extension of the file, you use the suffix property:

from pathlib import Path

path = Path('readme.txt')
print(path.suffix)Code language: Python (python)

Output:

.txtCode language: Python (python)

Checking if a path is file or directory

The is_file() method returns True if a path is a file or False otherwise. Likewise, the is_dir() reuturns True if a path is a directory or False otherwse.

from pathlib import Path


path = Path('readme.txt')
print(path.is_file())  # True

path = Path.cwd()
print(path.is_dir())  # TrueCode language: Python (python)

Using Python Path to interact with files

The Path objet allows you to create, rename, and delete files.

Creating a file

To create a file, you use the touch() method. For example, the following creates the readme.md file in the current working directory:

from pathlib import Path

path = Path('notes.md')
path.touch()Code language: Python (python)

To write text to a file, you use the write_text() method:

from pathlib import Path

path = Path('notes.md')
path.touch()
path.write_text('# Path is awesome')Code language: Python (python)

Note that you can also create a binary file and write bytes to it using the write_bytes() method.

Deleting a file

To delete a file, you use the unlink() method:

from pathlib import Path

path = Path('notes.md')
path.unlink()Code language: Python (python)

If the path doesn’t exist, the unlink() method will raise a FileNotFoundError exception. To avoid this, you can use the missing_ok argument:

from pathlib import Path

path = Path('notes.md')
path.unlink(missing_ok=True)Code language: Python (python)

Renaming a file

To rename a file, you use the rename() method. The following example creates the notes.md file, write a text into it, and rename its name to notes.txt:

from pathlib import Path

# create the notes.md
path = Path('notes.md')
path.touch()
path.write_text('My notes')

# rename nodes.md to notes.txt
path.rename('notes.txt')Code language: Python (python)

Listing files in a directory

The iterdir() method iterates over a directory. It returns a generator that yields the paths including both a path of a file or a directory.

To list all files in a directory, you can combine the iterdir() method with is_file() method. For example, the following lists all files in the downloads directory located inside the home directory:

from pathlib import Path


download_path = Path.home() / 'downloads'
for path in download_path.iterdir():
    if path.is_file():
        print(path)Code language: Python (python)

If you want to get a particular file type, you can use the suffix property. For example, the following lists all text files from the downloads directory:

from pathlib import Path


download_path = Path.home() / 'downloads'

for path in download_path.iterdir():
    if path.is_file() and path.suffix == '.txt':
        print(path)Code language: Python (python)

Or in a more pythonic way using a list comprehension:

from pathlib import Path


download_path = Path.home() / 'downloads'

file_paths = [path for path in download_path.iterdir()
              if path.is_file() and path.suffix == '.txt']
print(file_paths)Code language: Python (python)

Using Python Path to interact with directories

Like files, the Path also allows you to create, rename, and remove directories.

Creating a directory

To create a directory, you use the mkdir() method. The following example creates a test directory in the current working directory:

from pathlib import Path


path = Path('test')
path.mkdir()Code language: Python (python)

If the test directory exists, the mkdir() method will raise the FileExistsError exception. To avoid the exception if the directory already exists, you can use the exist_ok argument:

from pathlib import Path


path = Path('test')
path.mkdir(exist_ok=True)Code language: Python (python)

Renaming a directory

To rename a directory, you use the rename() method. For example, the following renames the directory test to tests (with additional s):

from pathlib import Path


path = Path('test')
path.rename('tests')Code language: Python (python)

Deleting a directory

To delete a directory, you use the rmdir() method. Note that the directory must be empty:

from pathlib import Path


path = Path('tests')
path.rmdir()Code language: Python (python)

If the directory doesn’t exist, the rmdir() method will raise a FileNotFoundErorr exception. To avoid this, you can check if the directory exists before calling the rmdir() method:

from pathlib import Path


path = Path('tests')

if path.exists():
    path.rmdir()Code language: Python (python)

Listing subdirectories

To list all subdirectories of a path, you use the iterdir() and is_dir() methods. For example, the following lists all subdirectories of the downloads path:

from pathlib import Path


download_path = Path.home() / 'downloads'

for path in download_path.iterdir():
    if path.is_dir():
        print(path)Code language: Python (python)

Or in a more pythonic way using a list comprehension:

from pathlib import Path


download_path = Path.home() / 'downloads'

paths = [path for path in download_path.iterdir() if path.is_dir()]
print(paths)Code language: Python (python)

Summary

DescriptionMethods / Properties
Create a new Path object from a stringPath('path/to/file/or/directory/')
Join paths using the / operatorpath = path1 / path2 / 'my_dir' / 'my_file.txt'
Get the path of the home directoryPath.home()
Get the path of the current working directoryPath.cwd()
Get the first parent directory of a pathpath.parent
Get the nth parent directory of a pathpath.parents[n]
Return True if a path is a filepath.is_file()
Return True if a path is a directorypath.is_dir()
Return True if a path existspath.exists()
Create a filepath.touch()
Write text to a filepath.write_text(contents)
Write bytes to a filepath.write_bytes(bytes)
Rename a file or directorypath.rename(target)
Delete a filepath.unlink()
Create a directorypath.mkdir()
Remove a directorypath.rmdir()
List files and/or directoriespath.iterdir()
Did you find this tutorial helpful ?