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\\'
Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .
So if you are in your home directory the full path is s.th. like /home/sosytee/my_script . For your home directory there is the "short-cut" ~ , meaning you can also write ~/my_script . But that will of course resolve to a different path for every user.
The best Linux command to get file path is using pwd command. To use this command, type “pwd” into your terminal and press enter. This command will print the current working directory. The output will be the file path.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With