path python code example
Example 1: PYTHON INSTALL DIR = os.path.dirname(os.path.dirname(os.__file__)) AttributeError: module 'os' has no attribute '_file_'
import os
path = "/home"
print(os.path.join(path, "User/Desktop", "file.txt"))
Example 2: pathlib path forward or back slahses
>>> import pathlib
>>> p = pathlib.PureWindowsPath(r'\dir\anotherdir\foodir\more')
>>> print(p)
\dir\anotherdir\foodir\more
>>> print(p.as_posix())
/dir/anotherdir/foodir/more
>>> str(p)
'\\dir\\anotherdir\\foodir\\more'
>>> str(p.as_posix())
'/dir/anotherdir/foodir/more'
Example 3: python path from string
from pathlib import Path
str_path = "my_path"
path = Path(str_path)
Example 4: windows how to store filepath as variabley python
from pathlib import Path
docs_folder = Path("some_folder/some_folder/")
text_file = docs_folder / "some_file.txt"
f = open(text_file)
Example 5: path in python
data_folder = "source_data/text_files/"
file_to_open = data_folder + "raw_data.txt"
f = open(file_to_open)
print(f.read())
Example 6: what does filename = path(file).stem python
from pathlib import Path
Path('/root/dir/sub/file.ext').stem