from pathlib import Path
import os43 Path
43.1 WD and Home
43.1.1 Current WD
# Same
os.getcwd()
#> '/Users/kittipos/my_book/py-notes/contents/basic'
Path.cwd()
#> PosixPath('/Users/kittipos/my_book/py-notes/contents/basic')On Windows, .cwd() returns a WindowsPath. On Linux and macOS, you get a PosixPath.
43.1.2 Current module
Path(__file__)
#> NameError: name '__file__' is not definedThe __file__ attribute contains the path to the file that Python is currently importing or executing
Parent module:
Path(__file__).parent.parent
#> NameError: name '__file__' is not defined43.1.3 Home Dir
Path.home()
#> PosixPath('/Users/kittipos')43.2 Path Operations
43.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
43.2.2 Absolute path
Path(".").absolute()
#> PosixPath('/Users/kittipos/my_book/py-notes/contents/basic')
Path(".").resolve() # Better
#> PosixPath('/Users/kittipos/my_book/py-notes/contents/basic')43.2.3 Check Existance
Path("somefile").exists()
#> False43.2.4 Glob
sorted(Path('.').glob('*.qmd'))
#> [PosixPath('comprehen.qmd'), PosixPath('cond.qmd'), PosixPath('ctr-flow-ex.qmd'), PosixPath('data-str.qmd'), PosixPath('dataclass.qmd'), PosixPath('exception.qmd'), PosixPath('file.qmd'), PosixPath('fun-prog.qmd'), PosixPath('function-02.qmd'), PosixPath('function-dec.qmd'), PosixPath('function-validate.qmd'), PosixPath('function.qmd'), PosixPath('json.qmd'), PosixPath('loop.qmd'), PosixPath('match-case.qmd'), PosixPath('number.qmd'), PosixPath('path.qmd'), PosixPath('pkg.qmd'), PosixPath('primitive.qmd'), PosixPath('regex-re2.qmd'), PosixPath('regex.qmd'), PosixPath('request.qmd'), PosixPath('string.qmd'), PosixPath('typing.qmd')]
# Or
# [x for x in Path('.').glob('*.qmd')]43.2.5 Join Path
Use slash /
Path.cwd() / Path("somefile.txt")
#> PosixPath('/Users/kittipos/my_book/py-notes/contents/basic/somefile.txt')Use joinpath()
Path.home().joinpath("python", "scripts", "test.py")
#> PosixPath('/Users/kittipos/python/scripts/test.py')43.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/contents/basic')
path.name
#> 'basic'
path.stem
#> 'basic'
path.suffix
#> ''
path.anchor
#> '/'
path.parent
#> PosixPath('/Users/kittipos/my_book/py-notes/contents')
path.parent.parent
#> PosixPath('/Users/kittipos/my_book/py-notes')