1517

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\\'
5
  • 16
    __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 a NameError, at least on python 2.7.3, but others too I guess. Commented May 31, 2015 at 1:04
  • 7
    Why. is. this. so. hard. There are like a dozen SO threads on this topic. Python: "Simple is better than complex...There should be one-- and preferably only one --obvious way to do it." Commented Feb 3, 2021 at 3:38
  • os.path.split(file_path)[0] Commented Nov 22, 2022 at 15:28
  • 2
    @eric it isn't hard, and the existence of multiple questions isn't evidence of something being hard - it's evidence of people not doing good research, of question titles being suboptimal for SEO, and/or of people failing to close duplicates that should be closed. Commented Jan 18, 2023 at 10:44
  • print(os.getcwd()) Commented Oct 18, 2023 at 16:44

12 Answers 12

2816

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.

Python 3

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()

Python 2 and 3

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.

References

  1. pathlib in the python documentation.
  2. os.path - Python 2.7, os.path - Python 3
  3. os.getcwd - Python 2.7, os.getcwd - Python 3
  4. what does the __file__ variable mean/do?
Sign up to request clarification or add additional context in comments.

30 Comments

abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!
should be os.path.dirname(os.path.abspath(os.__file__))?
@DrBailey: no, there's nothing special about ActivePython. __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.
I would recommend using realpath instead of abspath to resolve a possible symbolic link.
@cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt. \
|
209

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.

10 Comments

I had to do Path(__file__).parent to get the folder that is containing the file
That is correct @YellowPillow, Path(__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.
Sorry I should've have made this clearer, but if 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/module
@YellowPillow Path(__file__).cwd() is more explicit
Path(__file__) doesn't always work, for example, it doesn't work in Jupyter Notebook. Path().absolute() solves that problem.
|
113

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).

2 Comments

This should be the accepted answer as of 2019. One thing could be mentioned in the answer as well: one can immediately call .open() on such a Path object as in with Path(__file__).parent.joinpath('some_file.txt').open() as f:
The other issue with some of the answers (like the one from Ron Kalian, if I'm not mistaken), is that it will give you the current directory, not necessarily the file path.
29

Try this:

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

1 Comment

Best answer. This is the way I usually get the current script path, thanks.
19
import os
print(os.path.dirname(__file__))

3 Comments

Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.
It will give / as output
@sorin Actually on Python 3.6 they are both the same
8

for jupyter notebooks

In 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

  • by jupyter notebook and navigated manually to your notebook
  • directly by jupyter notebook tmp2/Untitled.ipynb

Info: 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.

2 Comments

This answer is not correct. 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.path
@bjmc yes and no. It works in jupyter notebooks, as the kernels working directory is equal to the notebooks directory. However this answer seems to help people, so I will modify it ...
7

I 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 !!!!

  1. dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
  2. Given that Path(__file__).is_absolute() is True, the use of the .absolute() method in dir3 appears redundant.
  3. The shortest command that works is dir4.

Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()

2 Comments

A bare 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.
@MisterMiyagi I have updated your comment to my answer. Thanks.
7

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

3 Comments

Thx. Works also perfect in JupyterLab
this is misleading absolute is cwd not where your file is placed. not guaranteed to be the same.
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.
2

Python 2 and 3

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\

1 Comment

On a 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 ...
0

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

8 Comments

The question isn't about IPython
@Kiro, my solution answers the question using IPython. For example If some one answers a question with a solution using a new library then also imho it remains a pertinent answer to the question.
@elli0t, partially agree. Consider someone using Jupyter notebook has this question for whom perhaps using %pwd magic command would be easier and preferable over os import.
The question isn't about getting the present working directory, it's about getting the directory of the script. Those two can be very different things.
@NafeezQuraishi: I don't know what you mean. The question is clearly asking about the path to the directory that the file is in, which may not be the current working directory. Those are two different concepts.
|
0

I have made a function to use when running python under IIS in CGI in order to get the current folder:

import os 
def getLocalFolder():
    path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
    return path[len(path)-1]

Comments

-1

This can be done without a module.

def get_path():
    return (__file__.replace(f"<your script name>.py", ""))
print(get_path())

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.