Object-oriented filesystem paths in Python (pathlib)

PythonProgrammingServer Side Programming

The pathlib module provides an object oriented approach to handling filesystem paths. The module also provides functionality appropriate for various operating systems. Classes defined in this module are of two types – pure path types and concrete path types. While pure paths can only perform purely computational operations, concrete paths are capable of doing I/O operations too.

pathlib module defines following classes −

Sr.No.Module & Description
1PurePath
The base class for all other classes
2Path
subclassed from PurePath. This is a concrete class that represents filesystem path.
3PosixPath
Path subclass for non-Windows OS
4WindowsPath
Path subclass for Windows systems
5PurePosixPath
PurePath subclass for non-Windows systems
6PureWindowsPath
PurePath subclass for Windows systems

When instance of Path class is created, it will automatically return either WindowsPath or PosixPath depending on your system.

Note that WindowsPath or PosixPath object can also be created directly, but not on system of same type only.

To create Path object use following syntax

>>> from pathlib import *
>>> p = Path(".")
>>> type(p)
<class 'pathlib.WindowsPath'>

You can see that since above statement is executed on Windows system, WindowsPath object is created. “.” Refers to current directory.

The Path class has following methods defined in it

absolute() − returns absolute version of Path object.

>>> p.absolute()
WindowsPath('C:/python36')

exists() − returns true if given path exists

>>> p = Path("mydir")
>>> p.exists()
False
>>> p = Path("etc")
>>> p.exists()
True

is_dir() − returns true if path is a directory

>>> p = Path("etc")
>>> p.is_dir()
True
>>> p = Path("test.py")
>>> p.is_dir()
False

is_file() − returns true if path corresponds to file

>>> p = Path("tmp.py")
>>> p.is_file()
True
>>> p = Path("etc")
>>> p.is_file()
False

iterdir() − returns a generator that yields filenames in the directory corresponding to path.

>>> p = Path("libs")
>>> for f in p.iterdir():
print (f)
libs\libpython36.a
libs\python3.lib
libs\python36.lib
libs\_tkinter.lib

mkdir() − creates new directory representing path if it is not already present.

>>> p = Path("mydir")
>>> p.mkdir()
>>> p.absolute()
WindowsPath('C:/python36/mydir')
>>> p = Path("codes")
>>> p.mkdir()
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'codes'

open() − opens file represented by Path object and returns file object. This is similar to built-in open() function.

>>> p = Path("Hello.py")
>>> f = p.open()
>>> f.readline()
'Hello Python'

read_bytes() − opens the file in binary mode, reads its data in binary form and closes the same.

>>> p = Path("Hello.py")
>>> f.read_bytes()
>>> p.read_bytes()
b'Hello Python'

read_text() − File is opened in text mode to read the text and close it afterwards.

>>> p = Path("Hello.py")
>>> p.read_text()
'Hello Python'

write_text() − opens the file, writes text and closes it.

>>> p = Path("Hello.py")
>>> p.write_text("Hello how are you?")
18

write_bytes() − Writes binary data in a file and closes the same.

>>> p = Path("Hello.py")
>>> p.write_bytes(b'I am fine')
9

stat() − returns information about this path.

>>> p.stat()
os.stat_result(st_mode = 16895, st_ino = 9570149208167477, st_dev = 1526259762, st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 0, st_atime = 1543085915, st_mtime = 1543085915, st_ctime = 1543085915)

rmdir() − removes directory corresponding to Path object.

>>> p = Path("mydir")
>>> p.rmdir()

Path.cwd() − This is a classmethod of Path class. returns path to current working directory

>>> Path.cwd()
WindowsPath('C:/python36')

Path.home() − This is a classmethod of Path class. returns path to home directory

>>> Path.home()
WindowsPath('C:/Users/acer')

The ‘/’ operator is used to build paths.

>>> p = Path(".")
>>> p1 = p/'codes'
>>> p1.absolute()
WindowsPath('C:/python36/codes')

In this article we learned the object oriented API to filesystem object as defined in pathlib module.

raja
Published on 07-Dec-2018 10:58:18
Advertisements