20  Path

from pathlib import Path
import os

20.1 WD and Home

20.1.1 Current WD

# Same
os.getcwd()
#> '/Users/kittipos/my_book/py-notes/basic'
Path.cwd()
#> PosixPath('/Users/kittipos/my_book/py-notes/basic')

On Windows, .cwd() returns a WindowsPath. On Linux and macOS, you get a PosixPath.

20.1.2 Current module

Path(__file__)
#> name '__file__' is not defined

The __file__ attribute contains the path to the file that Python is currently importing or executing

Parent module:

Path(__file__).parent.parent
#> name '__file__' is not defined

20.1.3 Home Dir

Path.home()
#> PosixPath('/Users/kittipos')

20.2 Path Operations

20.2.1 Passing as string

Path(r"C:\Users\philipp\realpython\file.txt")
#> PosixPath('C:\\Users\\philipp\\realpython\\file.txt')

use raw string literals (r'string') to represent Windows paths

20.2.2 Absolute path

Path(".").absolute()
#> PosixPath('/Users/kittipos/my_book/py-notes/basic')
Path(".").resolve()
#> PosixPath('/Users/kittipos/my_book/py-notes/basic')

20.2.3 Check Existance

Path("somefile").exists()
#> False

20.2.4 Glob

sorted(Path('.').glob('*.qmd'))
#> [PosixPath('cond.qmd'), PosixPath('ctr-flow-ex.qmd'), PosixPath('data-str.qmd'), PosixPath('exception.qmd'), PosixPath('file.qmd'), PosixPath('function-02.qmd'), PosixPath('function.qmd'), PosixPath('loop.qmd'), PosixPath('number.qmd'), PosixPath('oop.qmd'), PosixPath('path.qmd'), PosixPath('pkg.qmd'), PosixPath('primitive.qmd'), PosixPath('string.qmd')]
# Or
# [x for x in Path('.').glob('*.qmd')]

20.2.5 Join Path

Use slash /

Path.cwd() / Path("somefile.txt")
#> PosixPath('/Users/kittipos/my_book/py-notes/basic/somefile.txt')

Use joinpath()

Path.home().joinpath("python", "scripts", "test.py")
#> PosixPath('/Users/kittipos/python/scripts/test.py')

20.2.6 Path Component

conveniently available as properties. Basic examples include:

  • .name: The filename without any directory

  • .stem: The filename without the file extension

  • .suffix: The file extension

  • .anchor: The part of the path before the directories

  • .parent: The directory containing the file, or the parent directory if the path is a directory

from pathlib import Path
path = Path(".").cwd()
path
#> PosixPath('/Users/kittipos/my_book/py-notes/basic')

path.name
#> 'basic'

path.stem
#> 'basic'

path.suffix
#> ''

path.anchor
#> '/'

path.parent
#> PosixPath('/Users/kittipos/my_book/py-notes')

path.parent.parent
#> PosixPath('/Users/kittipos/my_book')