11

How do I find the directory of the running Python script from inside Python [3.3]? I have tried what was suggested at: How can I find script's directory? , but I get "Invalid syntax" and directed to "os" (And I did import os).

The closest I have got to the answer is: sys.argv[0], but that still includes the file name, so I cannot use it. Is there any other way?

The part where it says rundir = sys.argv[0] is where the suggested code will go:

import os, sys

rundir = sys.argv[0]
print("Running from" + rundir)
Guy Keogh
  • 549
  • 2
  • 5
  • 15

3 Answers3

43

To get the directory that contains the module you are running:

import os
path = os.path.dirname(os.path.realpath(__file__))

Or if you want the directory from which the script was invoked:

import os
path = os.getcwd()

From the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.

Depending on how the script is called, this may be a relative path from os.getcwd(), so os.path.realpath(__file__) will convert this to an absolute path (or do nothing is the __file__ is already an absolute path). os.path.dirname() will then return the full directory by stripping off the filename.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

Try this:

import os
os.path.dirname(__file__)

__file__ gets the name of the file you are in. The dirname function gets the directory that the file is in.

The syntax error probably had to do with the print statement. In python 3.x

print "hi"

is invalid. Print is now a function.

print("hi")

works. You need the parentheses.

Brad Campbell
  • 2,969
  • 2
  • 23
  • 21
1

This should work:

import os,sys
print(os.path.dirname(os.path.realpath(sys.argv[0])))
Jahid
  • 21,542
  • 10
  • 90
  • 108