Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding out absolute path to a file from python

People also ask

How do I get the path of a Python file executed?

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

How do I find the path of a specific file?

To view the full path of an individual file: Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document.

How do I find the relative path of a file in Python?

A relative path starts with / , ./ or ../ . To get a relative path in Python you first have to find the location of the working directory where the script or module is stored. Then from that location, you get the relative path to the file want.


Here's how to get the directory of the current file:

import os
os.path.abspath(os.path.dirname(__file__))

the answer is to use:

 __file__

which returns a relative path.

os.path.abspath(__file__) 

can be used to get the full path.


The answers so far have correctly pointed you to os.path.abspath, which does exactly the job you requested. However don't forget that os.path.normpath and os.path.realpath can also be very useful in this kind of tasks (to normalize representation, and remove symbolic links, respectively) in many cases (whether your specific use case falls among these "many" is impossible to tell from the scant info we have, of course;-).


import os
dirname, filename = os.path.split(os.path.abspath(__file__))