In Perl, the FindBin
module is used to locate the directory of the original script. What's the canonical way to get this directory in Python?
Some of the options I've seen:
os.path.dirname(os.path.realpath(sys.argv[0]))
os.path.abspath(os.path.dirname(sys.argv[0]))
os.path.abspath(os.path.dirname(__file__))
To update on the previous answers, with Python 3.4+, you can now do:
import pathlib
bindir = pathlib.Path(__file__).resolve().parent
Which will give you the same, except you'll get a Path object that is way more nice to work with.
You can try this:
import os
bindir = os.path.abspath(os.path.dirname(__file__))
That will give you the absolute path of the current file's directory.
I don't use Python very often so I do not know if there is package like FindBin but
import os
import sys
bindir = os.path.abspath(os.path.dirname(sys.argv[0]))
should work.
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