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.
+3
A:
Use the __file__
variable:
os.path.join(os.path.dirname(__file__), "b.txt")
Martin v. Löwis
2009-08-22 07:37:05
+1
A:
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")
RichieHindle
2009-08-22 07:38:22