Pathlib

File and directory access

The OS library in python which handles almost all the basic file system operations. Now the Pathlib , which is a built-in python library. it is intuitive in terms of syntax, easier to use, and has more features out of the box. Paths are not strings.

Show Current Directory

from pathlib import Path

# Current Working Directory
Path.cwd()


# User Home Directory
home_dir = Path.home()

# Relative path to the current folder
p = Path()  # PosixPath('.')


# Parent of path

p.parent

The OS library will return a string, whereas the Pathlib will return an object of PosixPath.

circle-check

Component of Path

Check Directory of File Existing

OS Library

The function os.path.exists(str_path) takes a string type argument, which can be either the name of a directory or a file.

Pathlib

When using the Pathlib, we simply pass the path as a string to the "Path" class, which will give us a "PosixPath" object.

Create a Directory

The function mkdir() accepts a flag exist_ok . When it is set to true, the FileExistsError error is automatically ignored. When its parent directories are not existing. we just need to set the flag parents to true.

Creating a path by passing folder and filename

Relative path to another path

Comparing two paths

Join Path

File or directory

Moving files with pathlib

Copy file

Path touch

Show Directory Content

When we want to show the content of a directory.

The OS library doesn't provide the feature to search files using wildcards. Therefore, we have to import another library called Glob to help.

Quick Read/Write to File

Metadata of the File

Converting a relative path to an absolute path

Last updated