Python Pathlib Module Examples

Python pathlib module provides a set of object-oriented classes. These classes can represent paths on various operating systems. Programs can operate directory paths through these classes. The classes under pathlib module are as follows.

  1. PurePath: PurePath is only responsible for performing operations on the path string. It does not care whether the string corresponds to the real path or not. PurePath has two subclasses, PurePosixPath which represents UNIX style paths (including Mac OS X), and PureWindowsPath that represent windows style paths respectively.
  2. Path: Represents the “real path” of the file system. The Path object can be used to determine whether the corresponding file exists, whether it is a file, whether it is a directory, etc. Path also has two subclasses, PosixPath and WindowsPath.

1. Basic Functions of PurePath.

A python program can create a PurePath object by using PurePath or its two subclasses. If an object is created by using PurePath on UNIX or Mac OS X system, the program actually returns the PurePosixPath object. If an object is created by using PurePath on the Windows system, the program actually returns the PureWindowsPath object. If the program explicitly wants to create PurePosixPath or PureWindowsPath object, it should directly use the subclass of PurePath.

When a Python program creates a PurePath or a Path object, it can pass in either a single path string or multiple path strings, and PurePath will splice multiple path strings into one string. Please see below code example.

# Import all classes from pathlib module.
>>> from pathlib import *
>>> 
# Create a PurePath object.
>>> pp = PurePath('./test.py')
>>> 
>>> print(pp)
test.py
>>> 
# The object real type is pathlib.PurePosixPath class.
>>> print(type(pp))
<class 'pathlib.PurePosixPath'>
>>> 
# Create PurePath object with multiple path strings.
>>> pp = PurePath('usr','local/etc','test.py')
>>> 
>>> print(pp)
usr/local/etc/test.py
>>> 
# Create PurePosixPath object with multiple path string.
>>> pp = PurePosixPath('usr','local/etc','test.py')
>>> 
>>> print(pp)
usr/local/etc/test.py

If no parameters are passed in when creating a PurePath object, it will create a PurePath object representing the current path by default, which is equivalent to passing in a dot (representing the current path) as a parameter.

>>> pp = PurePath()
>>> 
>>> print(pp)
.

If the parameter passed in when creating a PurePath object contains multiple root paths, only the last root path, and the subsequent sub-paths will take effect.

# Only the /etc/framework take effect.
>>> pp = PurePath('/usr', '/etc', 'framework')
>>> 
>>> print(pp)
/etc/framework
>>> 
# Only thre d:/python take effect.
>>> pp = PureWindowsPath('c:/java', 'd:/python')
>>> 
>>> print(pp)
d:\python

It should be noted that in the Windows-style path, only the drive letter can be regarded as the root path.

>>> pp = PureWindowsPath('c:\java', '/python')
>>> 
>>> print(pp)
c:\python

If the path string passed in when creating the PurePath object contains redundant slashes and dots, the system will ignore them. But it will not ignore two dots, because two dots represent the parent path of current directory.

>>> pp = PurePath('/usr//lcoal')
>>> 
>>> pp
PurePosixPath('/usr/lcoal') # ignore //
>>> 
>>> pp = PurePath('/usr/./lcoal')
>>> 
>>> pp
PurePosixPath('/usr/lcoal') # ignore .
>>> 
>>> pp = PurePath('/usr/../lcoal')
>>> 
>>> pp
PurePosixPath('/usr/../lcoal') # does not ignore ..

2. PurePath Attributes & Methods Example.

PurePath provides many properties and methods, which are mainly used to manipulate path strings. Since PurePath does not really perform file operations and does not care whether the path string related OS path exist or not, these operations are somewhat similar to string methods.

>>> from pathlib import *
>>> 
>>> pp = PureWindowsPath('c:/windows')
# the drive property.
>>> print(pp.drive)
c:
>>> 
>>> pp = PurePosixPath('/usr')
>>> print(pp.drive)
# the root property.
>>> print(pp.root)
/
# the anchor property.
>>> print(pp.anchor)
/
>>> pp = PurePath('/usr/local/java')
>>> 
# the parent property.
>>> pp.parent
PurePosixPath('/usr/local')
>>>
# the parents property.
>>> pp.parents[0]
PurePosixPath('/usr/local')
>>> pp.parents[1]
PurePosixPath('/usr')
>>> pp.parents[2]
PurePosixPath('/')
>>> 
# the name property.
>>> pp = PurePath('/usr/local')
>>> 
>>> print(pp.name)
local
>>>
>>> pp = PurePath('/usr/local/test.txt.png.zip')
>>> 
# the suffix property.
>>> print(pp.suffix)
.zip
# the stem property.
>>> print(pp.stem)
test.txt.png
>>> 
# the suffixes property.
>>> print(pp.suffixes[0])
.txt
>>> print(pp.suffixes[1])
.png
>>> print(pp.suffixes[2])
.zip

# determines whether the current path matches the specified wildcard.
>>> pp = PurePath('/usr/local/test.py')
>>> 
>>> print(pp.match('*.py'))
True
>>> print(pp.match('cal/*.py'))
False
>>> print(pp.match('local/*.py'))
True


# test relative_to method.
>>> pp = PurePosixPath('/usr/local/java')
>>> 
>>> print(pp.relative_to('/usr'))
local/java
>>> 
>>> print(pp.relative_to('/usr/local'))
java



# test with_name method.
>>> pp = PurePosixPath('/usr/local/java')
>>> 
>>> print(pp.with_name('python'))
/usr/local/python


# test with_suffix method.
>>> pp = PurePosixPath('/usr/local/java')
>>> 
>>> print(pp.with_suffix('.txt'))
/usr/local/java.txt

3. Path Attributes & Methods Example.

Path is a subclass of PurePath. In addition to supporting various operations, properties, and methods of PurePath, it can actually access the underlying file system, including check whether the path exists or not, obtaining various properties of the path (such as read-only, file or folder, etc.), and even reading and writing files.

>>> from pathlib import *
>>> 
# Get current directory Path object.
>>> p = Path('.')
>>> 
# Traverse current directory and print each file and subdirectory in the current directory.
>>> for dir in p.iterdir():
...     print(dir)

# Get the upper level directory
>>> p = Path('../')
>>>
# Get *.py files under the superior directory and all its subdirectories
>>> for x in p.glob('**/*.py')
...     print(x)

# Get Path object by folder path '/usr/local'.
>>> p = Path('/usr/local')
>>>
# Get test.py file in path '/usr/local' and all it's subdirectories.
>>> for x in p.glob('**/test.py')
...     print(x)


# Create a new file in the current directory.
>>> p = Path('./abc.txt')
>>>
# Write text to the file use utf-8 character set encoding.
>>> res = p.write_text('hello python pathlib.',encoding='utf-8')
>>>
# The return value is write character count.
>>> print(res)
21
# Read data from the file with utf-8 character set encoding.
>>> data = p.read_text(encoding='utf-8')
>>> 
>>> print(data)
hello python pathlib.
>>> 
>>> 
# Read bytes value from the file.
>>> bb = p.read_bytes()
>>> 
>>> print(bb)
b'hello python pathlib.'

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky