简体   繁体   中英

Query current directory in Python (the one the script is running from)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM