How do I get the full path of the current file’s directory? [duplicate]
__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.
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 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.
12 Answers 12
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
abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!
@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.
@cph2117: this will only work if you run it in a script. There is no __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.
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
Path(__file__) doesn’t always work, for example, it doesn’t work in Jupyter Notebook. Path().absolute() solves that problem.
from pathlib import Path path = Path(__file__).parent.absolute()
- 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) .
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.
import os dir_path = os.path.dirname(os.path.realpath(__file__))
import os print(os.path.dirname(__file__))
Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.
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=\ndir2=\ndir3=\ndir4=')
- dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
- Given that Path(__file__).is_absolute() is True , the use of the .absolute() method in dir3 appears redundant.
- The shortest command that works is dir4.
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.
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
How can I find path to given file?
I have a file, for example «something.exe» and I want to find path to this file
How can I do this in python?
6 Answers 6
Perhaps os.path.abspath() would do it:
import os print os.path.abspath("something.exe")
If your something.exe is not in the current directory, you can pass any relative path and abspath() will resolve it.
use os.path.abspath to get a normalized absolutized version of the pathname
use os.walk to get it’s location
import os exe = 'something.exe' #if the exe just in current dir print os.path.abspath(exe) # output # D:\python\note\something.exe #if we need find it first for root, dirs, files in os.walk(r'D:\python'): for name in files: if name == exe: print os.path.abspath(os.path.join(root, name)) # output # D:\python\note\something.exe
if you absolutely do not know where it is, the only way is to find it starting from root c:\
import os for r,d,f in os.walk("c:\\"): for files in f: if files == "something.exe": print os.path.join(r,files)
else, if you know that there are only few places you store you exe, like your system32, then start finding it from there. you can also make use of os.environ[«PATH»] if you always put your .exe in one of those directories in your PATH variable.
for p in os.environ["PATH"].split(";"): for r,d,f in os.walk(p): for files in f: if files == "something.exe": print os.path.join(r,files)
Just to mention, another option to achieve this task could be the subprocess module, to help us execute a command in terminal, like this:
import subprocess command = "find" directory = "/Possible/path/" flag = "-iname" file = "something.foo" args = [command, directory, flag, file] process = subprocess.run(args, stdout=subprocess.PIPE) path = process.stdout.decode().strip("\n") print(path)
With this we emulate passing the following command to the Terminal: find /Posible/path -iname «something.foo» . After that, given that the attribute stdout is binary string, we need to decode it, and remove the trailing «\n» character.
I tested it with the %timeit magic in spyder, and the performance is 0.3 seconds slower than the os.walk() option.
I noted that you are in Windows, so you may search for a command that behaves similar to find in Unix.
Finally, if you have several files with the same name in different directories, the resulting string will contain all of them. In consequence, you need to deal with that appropriately, maybe using regular expressions.