python directory path code example

Example 1: python get current file location

import os
os.path.dirname(os.path.abspath(__file__))

Example 2: get current working directory python

# print current working directory in python
import os
cwd = os.getcwd()
print(cwd)

Example 3: python how to open a file in a different directory in mac

import os
f = open (os.path.expanduser("~/Desktop/somedir/somefile.txt"))

Example 4: python file location path

import os

print('getcwd:      ', os.getcwd())
print('__file__:    ', __file__)

Example 5: file path in python for windows

outputFileName = 'Destination/With/Forward/Slash/filename.txt'

Example 6: python path from string

from pathlib import Path
str_path = "my_path"
path = Path(str_path)