Lightning talk: pathlib - PEP 428

A high level, object oriented alternitive to os.path

In [1]:
import pathlib

Documentation:

Top-level classes

PurePaths

In [2]:
from pathlib import PurePath, PurePosixPath, PureWindowsPath
In [3]:
PurePath()
Out[3]:
PurePosixPath('.')
In [4]:
PureWindowsPath('foo/bar') == PureWindowsPath('foo\\bar')
Out[4]:
True
In [5]:
PurePosixPath('foo') == PurePosixPath('FOO')
Out[5]:
False
In [6]:
PureWindowsPath('foo') == PureWindowsPath('FOO')
Out[6]:
True
In [7]:
PurePath('foo', 'bar', 'baz')
Out[7]:
PurePosixPath('foo/bar/baz')
In [8]:
PurePath('foo') / 'bar' / 'baz'
Out[8]:
PurePosixPath('foo/bar/baz')
In [9]:
str(PurePath('foo', 'test.txt'))
Out[9]:
'foo/test.txt'

PurePath Properties

In [10]:
pp = PurePath('/usr/bin/python3')
pp.parts
Out[10]:
('/', 'usr', 'bin', 'python3')
In [11]:
list(pp.parents)
Out[11]:
[PurePosixPath('/usr/bin'), PurePosixPath('/usr'), PurePosixPath('/')]
In [12]:
pp.parent
Out[12]:
PurePosixPath('/usr/bin')
In [13]:
pp.name
Out[13]:
'python3'
In [14]:
pp = PurePath('my/library/data.tar.gz')
pp.suffix
Out[14]:
'.gz'
In [15]:
pp.suffixes
Out[15]:
['.tar', '.gz']
In [16]:
pp.match('*.tar.gz')
Out[16]:
True
In [17]:
pp.match('*.py')
Out[17]:
False

Concrete paths

In [18]:
from pathlib import Path
In [19]:
Path.cwd()
Out[19]:
PosixPath('/Users/wto/python3')
In [20]:
Path('test.txt').absolute()
Out[20]:
PosixPath('/Users/wto/python3/test.txt')
In [21]:
list(Path.cwd().iterdir())
Out[21]:
[PosixPath('/Users/wto/python3/.DS_Store'),
 PosixPath('/Users/wto/python3/.ipynb_checkpoints'),
 PosixPath('/Users/wto/python3/hi.txt'),
 PosixPath('/Users/wto/python3/pathlib - PEP 428.ipynb'),
 PosixPath('/Users/wto/python3/pathlib - PEP 428.slides.html')]
In [22]:
p = Path('hi.txt')
p.exists() and p.is_file()
Out[22]:
True
In [23]:
print(p.open().read())
Well hello there!


Thanks!

Trevor Olson

twitter.com/ZombieFeynman