J.D
J.D

Reputation: 444

What is the path to the folder my Python script lies in?

I want my Python scripts to be able to be run by people with other folder set ups too, so using a reference to a folder the Python script is saved to makes a lot of sense.

Example: If my script, "script_1.py" is run from "C:\My Scripts\script_1.py" I want to save "C:\My Scripts" to a variable I can use.

However, I can't get it too work.

I've import os and sys, but using os.path.dirname(__file__) or os.path.abspath(__file__) gives the error message:

Traceback (most recent call last):

File "<ipython-input-24-1830932ce69b>", line 1, in <module>
os.path.dirname(__file__)

NameError: name '__file__' is not defined

Using sys.executable gives me the address to where my Python is installed (I think?? It doesn't give me what I'm looking for anyhow).

I was also given the advice to try os.environ['_'] but that gives:

Traceback (most recent call last):

File "<ipython-input-26-6c75f8b10c6d>", line 1, in <module>
os.environ['_']

File "D:\Continuum\Anaconda3\lib\os.py", line 669, in __getitem__
   raise KeyError(key) from None

KeyError: '_'

I'm running my code from Windows 10 by the way. It's Python 3.

Upvotes: 0

Views: 3084

Answers (1)

Alex Jadczak
Alex Jadczak

Reputation: 582

This will give you the location of your script.

import os
import sys
script_location = os.path.split(os.path.realpath(sys.argv[0]))[0]

Upvotes: 1

Related Questions