質問

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.

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top