from pathlib import Path
import os
31 Path
31.1 WD and Home
31.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.
31.1.2 Current module
__file__)
Path(#> NameError: name '__file__' is not defined
The __file__
attribute contains the path to the file that Python is currently importing or executing
Parent module:
__file__).parent.parent
Path(#> NameError: name '__file__' is not defined
31.1.3 Home Dir
Path.home()#> PosixPath('/Users/kittipos')
31.2 Path Operations
31.2.1 Passing as string
r"C:\Users\philipp\realpython\file.txt")
Path(#> PosixPath('C:\\Users\\philipp\\realpython\\file.txt')
use raw string literals (r'string'
) to represent Windows paths
31.2.2 Absolute path
".").absolute()
Path(#> PosixPath('/Users/kittipos/my_book/py-notes/basic')
".").resolve() # Better
Path(#> PosixPath('/Users/kittipos/my_book/py-notes/basic')
31.2.3 Check Existance
"somefile").exists()
Path(#> False
31.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.qmd'), PosixPath('json.qmd'), PosixPath('loop.qmd'), PosixPath('match-case.qmd'), PosixPath('number.qmd'), PosixPath('oop-abc.qmd'), PosixPath('oop.qmd'), PosixPath('path.qmd'), PosixPath('pkg.qmd'), PosixPath('primitive.qmd'), PosixPath('request.qmd'), PosixPath('string.qmd'), PosixPath('typing.qmd')]
# Or
# [x for x in Path('.').glob('*.qmd')]
31.2.5 Join Path
Use slash /
/ Path("somefile.txt")
Path.cwd() #> PosixPath('/Users/kittipos/my_book/py-notes/basic/somefile.txt')
Use joinpath()
"python", "scripts", "test.py")
Path.home().joinpath(#> PosixPath('/Users/kittipos/python/scripts/test.py')
31.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(".").cwd()
path
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')