22  File

from pathlib import Path

23 Path

Path("C:\\Program Files\\...")
#> PosixPath('C:\\Program Files\\...')

# Combine Path
Path("A") / Path("B")
#> PosixPath('A/B')

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

23.1 Path Operation

my_path = Path("file.qmd")

my_path.exists()
#> True
my_path.is_dir()
#> False
my_path.is_file()
#> True

my_path.absolute() # Absolute Value
#> PosixPath('/Users/kittipos/my_book/py-notes/basic/file.qmd')

my_path.name # File name
#> 'file.qmd'
my_path.stem # File name, no ext
#> 'file'
my_path.suffix # Ext
#> '.qmd'
my_path.parent # Parent Folder
#> PosixPath('.')

Change Name, Suffix, Stem

my_path = my_path.with_name("file.txt")
print(my_path)
#> file.txt

my_path = my_path.with_suffix(".py")
print(my_path)
#> file.py