Reputation: 454
Is there any way to query the absolute path of a script inside the script we want to know the location for? For instance if I save it on my Desktop, I would like to store into a variable the absolute location, I want it to return C:/Users/Doc/Desktop
.
I saw this piece of code in another guy's script but I don't know exactly if it is useful for what I am aiming to do: path = os.path.dirname(script.__file__)
Do you know how to implement that? Thanks in advance.
Upvotes: 0
Views: 226
Reputation: 1124708
Yes, __file__
is what you are looking for; but it can be a relative path.
Use:
here = os.path.basename(os.path.abspath(__file__))
to turn that into the directory path of the location of the script. os.path.abspath()
takes a relative path and turns it into an absolute path (using the current working directory as a reference); os.path.dirname()
splits off the filename from that path.
Upvotes: 2
Reputation: 23251
To get the path of the current script, use:
__file__
To get the directory from that:
os.path.dirname(__file__)
To get the current working directory (directory you were in when the script ran), use:
os.getcwd()
Upvotes: 3