How do I find the directory of the running Python script from inside Python [3.3]? I have tried what was suggested at: How can I find script's directory? , but I get "Invalid syntax" and directed to "os" (And I did import os).
The closest I have got to the answer is: sys.argv[0]
, but that still includes the file name, so I cannot use it. Is there any other way?
The part where it says rundir = sys.argv[0]
is where the suggested code will go:
import os, sys
rundir = sys.argv[0]
print("Running from" + rundir)
To get the directory that contains the module you are running:
import os
path = os.path.dirname(os.path.realpath(__file__))
Or if you want the directory from which the script was invoked:
import os
path = os.getcwd()
From the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file.
Depending on how the script is called, this may be a relative path from os.getcwd()
, so os.path.realpath(__file__)
will convert this to an absolute path (or do nothing is the __file__
is already an absolute path). os.path.dirname()
will then return the full directory by stripping off the filename.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With