pathlib Module

You can use the pathlib module to interact with file-paths on Windows or *nix-based systems.

i>>> from pathlib import Path
i>>> Path('spam', 'bacon', 'eggs')
PosixPath('spam/bacon/eggs')
i>>> str(Path('spam', 'bacon', 'eggs'))
'spam/bacon/eggs'

Note, for Windows systems this will return a WindowsPath object and corresponding path using back-slashes.

Concatenate paths #

You can use the / operator to concatenate Path objects and strings.

i>>> Path('spam') / 'bacon' / 'eggs'
PosixPath('spam/bacon/eggs')

Note this is safer than using string concatenation or the join() method when dealing with file-paths, especially if cross-platform compatibility is important.

Current working directory #

You can use the Path.cwd() to get the current working directory.

i>>> from pathlib import Path
i>>> import os
i>>> Path.cwd()
PosixPath('/home/akraker/wiki')
i>>> os.chdir('/home/akraker')
i>>> Path.cwd()
PosixPath('/home/akraker')

os.chdir() allows you to change directories.

Home directory #

i>>> Path.home()
PosixPath('/home/akraker')

Make dirs #

i>>> from pathlib import Path
i>>> Path(r'/home/akraker/test').mkdir()

Absolute vs relative paths #

  • absolute path always begins at root folder
  • relative path is relative to programs current working directory

There’s also the . and .. which is this directory and the parent directory, respectively.

Handling absolute and relative paths #

i>>> from pathlib import Path
i>>> Path.cwd()
PosixPath('/home/akraker')
i>>> Path.cwd().is_absolute()
True
i>>> Path('spam/bacon/eggs').is_absolute()
False
i>>> Path('my/relative/path')
PosixPath('my/relative/path')
i>>> Path.cwd() / Path('my/relative/path')
PosixPath('/home/akraker/my/relative/path')

The os module is also helpful for handling absolute/relative paths

i>>> import os
i>>> os.path.abspath('.')
'/home/akraker'
i>>> os.path.abspath('./bin'
i... )
'/home/akraker/bin'
i>>> os.path.isabs('.')
False
i>>> os.path.isabs(os.path.abspath('.'))
True
i>>> os.path.relpath('/home', '/')
'home'
i>>> os.path.relpath('/home', '/spam/eggs')
'../../home'

Getting the parts of a file-path #

i>>> p = Path('/home/akraker/test.txt')
i>>> p.anchor
'/'
i>>> p.parent
PosixPath('/home/akraker')
i>>> p.name
'test.txt'
i>>> p.stem
'test'
i>>> p.suffix
'.txt'
i>>> p.drive
''

There’s more… #

I didn’t take all the notes from this chapter in Automate The Boring Stuff, so review may be necessary or review the docs for the modules themselves.

See also #