4

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
  • 106,540
  • 116
  • 246
  • 346
  • 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

8

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
  • 338,267
  • 99
  • 616
  • 750
  • 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
  • 151,563
  • 33
  • 264
  • 304
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,920
  • 3
  • 38
  • 56
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
  • 2,077
  • 1
  • 12
  • 13