This may seem like a newbie question, but it is not. Some common approaches don\'t work in all cases:
This means using path = os.path.abs
My solution is:
import os
print(os.path.dirname(os.path.abspath(__file__)))
Simply add the following:
from sys import *
path_to_current_file = sys.argv[0]
print(path_to_current_file)
Or:
from sys import *
print(sys.argv[0])
import os
current_file_path=os.path.dirname(os.path.realpath('__file__'))
First, you need to import from inspect
and os
from inspect import getsourcefile
from os.path import abspath
Next, wherever you want to find the source file from you just use
abspath(getsourcefile(lambda:0))
See my answer to the question Importing modules from parent folder for related information, including why my answer doesn't use the unreliable __file__
variable. This simple solution should be cross-compatible with different operating systems as the modules os
and inspect
come as part of Python.
First, you need to import parts of the inspect and os modules.
from inspect import getsourcefile
from os.path import abspath
Next, use the following line anywhere else it's needed in your Python code:
abspath(getsourcefile(lambda:0))
From the built-in module os
(description below), the abspath
tool is imported.
OS routines for Mac, NT, or Posix depending on what system we're on.
Then getsourcefile
(description below) is imported from the built-in module inspect
.
Get useful information from live Python objects.
abspath(path)
returns the absolute/full version of a file pathgetsourcefile(lambda:0)
somehow gets the internal source file of the lambda function object, so returns '<pyshell#nn>'
in the Python shell or returns the file path of the Python code currently being executed.Using abspath
on the result of getsourcefile(lambda:0)
should make sure that the file path generated is the full file path of the Python file.
This explained solution was originally based on code from the answer at How do I get the path of the current executed file in Python?.
this solution is robust even in executables
import inspect, os.path
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))