python file path code example

Example 1: python get filename from path

import os
print(os.path.basename(your_path))

Example 2: find the path to a file python

import os
print os.path.abspath("something.exe")

Example 3: python file from path

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

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

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

Example 5: python file location path

import os

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

Example 6: python open file relative to script location

import os

path = 'a/relative/file/path/to/this/script/file.txt'

with open(os.path.join(os.path.dirname(__file__), path), 'r') as input_file:
    content = input_file.read()