3

I am trying to get the path of my python script.

I know 'sys.argv[0] gives me the path and the name of my python script.

how can I just get the path?

I tried:

 print sys.argv[0]
    path = sys.argv[0].split("/")
    scriptpath = "".join(path[0:-1])

But it does not add back the path separator.

michael
  • 99,904
  • 114
  • 238
  • 340
  • change `"".join(path[0:-1])` to `"/".join(path[0:-1])` if you had to have that specific solution for whatever reason :) – Jason Sperske Nov 21 '12 at 23:19

4 Answers4

7

Prefer to use __file__, like this:

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

Note: using sys.argv[0] may not work if you call the script via another script from another directory.

wim
  • 302,178
  • 90
  • 548
  • 690
  • Unfortunately this one doesn't work as intended, if you use PyInstaller, because it is unpacked into a temporary folder which then is (correctly) returned as the path of the `__file__`. In this case `dirname(realpath(sys.argv[0]))` works fine. – Christoph Jüngling Jan 14 '19 at 12:51
3

you're looking for os.path.dirname(), in case you might have a relative pathame, you need os.path.abspath() too

SingleNegationElimination
  • 144,899
  • 31
  • 254
  • 294
1

Don't try string operations on paths, use the os.path module instead. E.g.:

scriptpath = os.path.dirname(sys.argv[0])
Michael
  • 8,624
  • 3
  • 36
  • 54
0

From another Stackoverflow thread

import sys, os

print 'sys.argv[0] =', sys.argv[0]             
pathname = os.path.dirname(sys.argv[0])        
print 'path =', pathname
print 'full path =', os.path.abspath(pathname)
Community
  • 1
  • 1
aw4lly
  • 1,939
  • 1
  • 11
  • 12