1059
votes

I want to get the current file's directory path. I tried:

>>> os.path.abspath(__file__)
'C:\\python27\\test.py'

But how can I retrieve the directory's path?

For example:

'C:\\python27\\'
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.drevicko
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."eric

16 Answers

2127
votes

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 2.7, os.path 3.8
  3. os.getcwd 2.7, os.getcwd 3.8
  4. what does the __file__ variable mean/do?
133
votes

Using Path 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__  

Documentation: pathlib

Note: If using Jupyter Notebook, __file__ doesn't return expected value, so Path().absolute() has to be used.

69
votes

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

12
votes
import os
print os.path.dirname(__file__)
10
votes

Try this:

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

USEFUL PATH PROPERTIES IN PYTHON:

 from pathlib import Path

    #Returns the path of the directory, where your script file is placed
    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

4
votes

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

4
votes

You can use os and os.path library easily as follows

import os
os.chdir(os.path.dirname(os.getcwd()))

os.path.dirname returns upper directory from current one. It lets us change to an upper level without passing any file argument and without knowing absolute path.

os.path.dirname(os.path.abspath(myfilename))

3
votes

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
1
votes

To keep the migration consistency across platforms (macOS/Windows/Linux), try:

path = r'%s' % os.getcwd().replace('\\','/')
1
votes

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('\\')
        return path[len(path)-1]
1
votes
## 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
1
votes

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)
0
votes

If you just want to see the current working directory

import os
print(os.getcwd())

If you want to change the current working directory

os.chdir(path)

path is a string containing the required path to be moved. e.g.

path = "C:\\Users\\xyz\\Desktop\\move here"
0
votes

This is what I got to work

    path = os.getcwd().replace(os.sep, "/")
    name = Path(__file__).name
    full = str(path) + "/" + str(name)
    indv = full.split("/")
-1
votes

System: MacOS

Version: Python 3.6 w/ Anaconda

import os

rootpath = os.getcwd()

os.chdir(rootpath)