Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

Returning source code file path at runtime

Can I find out the location of my .py source code when it is running? I need this so that I can save files into the same directory where the program is located. Thanks.
2 Solutions
Try this:

import sys
print sys.argv[0]
import os
currentWorkingDirectory = os.getcwd()

Depending on your platform, sys.argv[0] may or may not be useful.

sys.argv contains a list of all the command-line parameters used to invoke Python. If, for example, you use this:

python /home/barry/codeTest.py

then sys.argv[0] will either be '/home/barry/codeTest.py' or 'codeTest.py' (the reference manual says, "it is operating system dependent whether this is a full pathname or not"). One of those tells you where your file is and one doesn't.

The os.getcwd will consistently return your current working directory, but that may not always be useful either. For example, you may not actually be working out of your working directory. If I have a Python file called pathTest.py in /home/barry, but my current working directory is /home/barry/python, I can use this to invoke the script:
python ../pathTest.py

os.getcwd() would be listed as /home/barry/python, which is not where my file actually is.

You may need to experiment with some combination of these two on whatever OS you'll be running on to see if sys.argv[0] gives you a complete path, and then use that and os.getcwd() to figure out where your file is relative to the current working directory (if the file path is not absolute).

Hope this helps.

-- b.r.t.

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now