I want to get the current file\'s directory path. I tried:
>>> os.path.abspath(__file__)
\'C:\\\\python27\\\\test.py\'
But how can
## IMPORT MODULES
import os
## CALCULATE FILEPATH VARIABLE
filepath = os.path.abspath('') ## ~ os.getcwd()
## TEST TO MAKE SURE os.getcwd() is EQUIVALENT ALWAYS..
## ..OR DIFFERENT IN SOME CIRCUMSTANCES
To keep the migration consistency across platforms (macOS/Windows/Linux), try:
path = r'%s' % os.getcwd().replace('\\','/')
import os
print os.path.dirname(__file__)
Using Path
is the recommended way since Python 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute())
Documentation: pathlib
Note: If using Jupyter Notebook, __file__
doesn't return expected value, so Path().absolute()
has to be used.
I found the following commands will all return the full path of the parent directory of a Python 3.6 script.
Python 3.6 Script:
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 script
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer
dir3 = Path(__file__).parent.absolute() #See @Arminius answer
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}')
Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
Let's assume you have the following directory structure: -
main/ fold1 fold2 fold3...
folders = glob.glob("main/fold*")
for fold in folders:
abspath = os.path.dirname(os.path.abspath(fold))
fullpath = os.path.join(abspath, sch)
print(fullpath)