python os get file path code example

Example 1: python get filename from path

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

Example 2: get full path of file python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Example 3: python get path of current file

import pathlib
pathlib.Path(__file__).parent.absolute()

Example 4: python get path of file

>>> import os
>>> filepath="/media/rtsuse/some/random/filepath/with/logfile.log"
>>> os.path.dirname(filepath)
'/media/rtsuse/some/random/filepath/with'

Example 5: get path from file path python

>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
('T:\\Data\\DBDesign', 'DBDesign_93_v141b.mdb')

Example 6: get path of open file python

>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'