0

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.

2 Answers 2

3

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()

os.getcwd documentation

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.