How do I get the current file's directory path? I tried:
>>> os.path.abspath(__file__)
'C:\\python27\\test.py'
But I want:
'C:\\python27\\'
The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.
__file__ (note that it's two underscores on either side of the word) is a standard part of python. It's not available in C-based modules, for example, but it should always be available in a python script.__file__ if running from an interactive prompt. \Using Path from pathlib is the recommended way since Python 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.
Path(__file__).parent to get the folder that is containing the filePath(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.Path().absolute() exists in some module located at path/to/module and you're calling the module from some script located at path/to/script then would return path/to/script instead of path/to/modulePath(__file__).cwd() is more explicitPath(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__) is the path to the current file..parent gives you the directory the file is in..absolute() gives you the full absolute path to it.Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).
.open() on such a Path object as in with Path(__file__).parent.joinpath('some_file.txt').open() as f:Try this:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
import os
print(os.path.dirname(__file__))
/ as outputjupyter notebooksIn jupyter notebooks the __file__ variable is not available. However, the kernels working directory is equal to the notebooks location. Hence you can use
option 1
%cwd
option 2
from pathlib import Path
Path.cwd()
option 3
import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
This works if you called your notebook
jupyter notebook and navigated manually to your notebookjupyter notebook tmp2/Untitled.ipynbInfo: Using pathlib, is the object oriented (and recommended) way of handling paths in python 3.
Thanks for @bjmc for your comment, pointing out that this solution was actually accessing the working directory.
sys.path[0] contains the current working directory for the python interpreter, not the directory where the Python source code file exists. docs.python.org/3/library/sys.html#sys.pathI found the following commands return the full path of the parent directory of a Python 3 script.
Python 3 Script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 and above 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
dir4 = Path(__file__).parent
print(f'dir1={dir1}\ndir2={dir2}\ndir3={dir3}\ndir4={dir4}')
REMARKS !!!!
dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.Path(__file__).is_absolute() is True, the use of the .absolute() method in dir3 appears redundant.Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
Path() does not provide the script/module directory. It is equivalent to Path('.') – the current working directory. This is equivalent only when running a script located in the current working directory, but will break in any other case.USEFUL PATH PROPERTIES IN PYTHON:
from pathlib import Path
#Returns the path of the current directory
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))
#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))
#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))
#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))
#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))
OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED
Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2
File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv
isfileExist : True
isadirectory : False
File extension : .csv
Path() is the current working directory, not the directory of the script. This only "works" in the few cases where the script actually is in the current working directory.You can simply also do:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
Which outputs something like:
C:\my_folder\sub_folder\
windows 7 machine with python3.8.10 that I just tested it , for some reason __file__ doesn't seem to return any path but only just the file-name. Just saying in case anyone else ...IPython has a magic command %pwd to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd can be used directly as following:
present_working_directory = %pwd
__file__is not defined when you run python as an interactive shell. The first piece of code in your question looks like it's from an interactive shell, but would actually produce aNameError, at least on python 2.7.3, but others too I guess.