Skip to content

Instantly share code, notes, and snippets.

@atultherajput
Created February 27, 2019 11:14
Show Gist options
  • Save atultherajput/a14e9c14aa7a38e8c0010df30695e4a9 to your computer and use it in GitHub Desktop.
Save atultherajput/a14e9c14aa7a38e8c0010df30695e4a9 to your computer and use it in GitHub Desktop.
Get absolute path by giving relative path in python
#!/usr/bin/env python
import os
def current_dir():
abspath = os.path.abspath(__file__)
print('abspath: ' + abspath)
dirname = os.path.dirname(abspath)
print('dirname: ' + dirname)
return dirname
def new_path(dirname, relpath):
return os.path.join(dirname, relpath)
def extract_dir(filepath):
drive, path_and_file = os.path.splitdrive(filepath)
path, filename = os.path.split(path_and_file)
return path, filename
def get_path(relpath):
print('relpath: ' + relpath)
dirname = current_dir()
filepath = new_path(dirname, relpath)
print('filepath: ' + filepath)
path, filename = extract_dir(filepath)
print('path: ' + path, 'filename: ' + filename)
get_path('doc/example.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment