6.5. OS Pathlib
6.5.1. Extensions
import pathlib
pathlib.Path('my/library/setup.py').suffix # '.py'
pathlib.Path('my/library.tar.gz').suffix # '.gz'
pathlib.Path('my/library').suffix # ''
pathlib.Path('my/library.tar.gar').suffixes # ['.tar', '.gar']
pathlib.Path('my/library.tar.gz').suffixes # ['.tar', '.gz']
pathlib.Path('my/library').suffixes # []
6.5.2. Filenames
import pathlib
pathlib.Path('//some/share/setup.py').name # 'setup.py'
pathlib.Path('//some/share').name # ''
pathlib.Path('my/library.tar.gz').stem # 'library.tar'
pathlib.Path('my/library.tar').stem # 'library'
pathlib.Path('my/library').stem # 'library'
6.5.3. System os
vs. pathlib
|
|
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6.5.4. .home()
import pathlib
pathlib.home() # WindowsPath('C:/Users/José')
6.5.5. .drive
import pathlib
PureWindowsPath('c:/Program Files/').drive # 'c:'
PureWindowsPath('/Program Files/').drive # ''
PurePosixPath('/etc').drive # ''
6.5.6. .parents
import pathlib
p = PureWindowsPath('c:/foo/bar/setup.py')
p.parents[0] # PureWindowsPath('c:/foo/bar')
p.parents[1] # PureWindowsPath('c:/foo')
p.parents[2] # PureWindowsPath('c:/')
6.5.7. .parent
import pathlib
p = PurePosixPath('/a/b/c/d')
p.parent # PurePosixPath('/a/b/c')
6.5.8. .as_posix()
import pathlib
p = PureWindowsPath('c:\\windows')
str(p) # 'c:\\windows'
p.as_posix() # 'c:/windows'
6.5.9. .as_uri()
import pathlib
p = PurePosixPath('/etc/passwd')
p.as_uri() # 'file:///etc/passwd'
p = PureWindowsPath('c:/Windows')
p.as_uri() # 'file:///c:/Windows'
6.5.10. Path.chmod()
import pathlib
p = Path('setup.py')
oct(p.stat().st_mode) # 0o100775
p.chmod(0o444)
oct(p.stat().st_mode) # 0o100444
6.5.11. .glob()
import pathlib
sorted(Path('.').glob('*.py'))
# [PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
sorted(Path('.').glob('*/*.py'))
# [PosixPath('docs/conf.py')]
sorted(Path('.').glob('**/*.py'))
# [PosixPath('docs/conf.py'), ...]
6.5.12. .iterdir()
import pathlib
p = Path('docs')
for child in p.iterdir():
print(child)
# PosixPath('docs/conf.py')
# PosixPath('docs/index.rst')
# PosixPath('docs/Makefile')
# PosixPath('docs/_build')
# PosixPath('docs/_static')
# PosixPath('docs/_templates')
6.5.13. joining paths
from pathlib import Path
directory = Path("/etc")
filepath = directory / "my_file.txt"
if filepath.exists():
print('ok')