Let's say I have the files a.py and b.txt in the same directory. I can't garuntee where that directory is, but I know b.txt will be in the same directory as a.py. a.py needs to access b.txt, how would I go about finding the path to b.txt? Something like "./b.txt" won't work if the user runs the program from a directory other than the one it's saved in.
If you want the location of the main script, even from code that might be running in an imported module, you need to use sys.argv[0] rather than __file__. (sys.argv[0] is always the path to the main script; see http://docs.python.org/library/sys.html#sys.argv)
If you want the location of the current module, even if it's been imported by some other script, you should use __file__ as Martin says.
Here's a way to use sys.argv[0]:
import os, sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print os.path.join(dirname, "b.txt")
Use the __file__ variable:
os.path.join(os.path.dirname(__file__), "b.txt")
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