Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the full path of the current file's directory?

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\\' 
like image 720
Shubham Avatar asked Aug 07 '10 12:08

Shubham


People also ask

How do I find the current file path?

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

What is the full path to your home directory?

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.

How do I find the full path in Linux?

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.


2 Answers

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?
like image 138
Bryan Oakley Avatar answered Oct 15 '22 13:10

Bryan Oakley


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.

like image 30
Ron Kalian Avatar answered Oct 15 '22 14:10

Ron Kalian