A high level, object oriented alternitive to os.path
import pathlib
from pathlib import PurePath, PurePosixPath, PureWindowsPath
PurePath()
PurePosixPath('.')
PureWindowsPath('foo/bar') == PureWindowsPath('foo\\bar')
True
PurePosixPath('foo') == PurePosixPath('FOO')
False
PureWindowsPath('foo') == PureWindowsPath('FOO')
True
PurePath('foo', 'bar', 'baz')
PurePosixPath('foo/bar/baz')
PurePath('foo') / 'bar' / 'baz'
PurePosixPath('foo/bar/baz')
str(PurePath('foo', 'test.txt'))
'foo/test.txt'
pp = PurePath('/usr/bin/python3')
pp.parts
('/', 'usr', 'bin', 'python3')
list(pp.parents)
[PurePosixPath('/usr/bin'), PurePosixPath('/usr'), PurePosixPath('/')]
pp.parent
PurePosixPath('/usr/bin')
pp.name
'python3'
pp = PurePath('my/library/data.tar.gz')
pp.suffix
'.gz'
pp.suffixes
['.tar', '.gz']
pp.match('*.tar.gz')
True
pp.match('*.py')
False
from pathlib import Path
Path.cwd()
PosixPath('/Users/wto/python3')
Path('test.txt').absolute()
PosixPath('/Users/wto/python3/test.txt')
list(Path.cwd().iterdir())
[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')]
p = Path('hi.txt')
p.exists() and p.is_file()
True
print(p.open().read())
Well hello there!