Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the path of the Python script I am running in? [duplicate]

Tags:

python

path

People also ask

How do I find the path of a Python script?

getcwd() method. The os. getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.

How do you get the path for a file in the same folder Python?

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys. path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.

What does __ file __ mean in Python?

__file__ is a variable that contains the path to the module that is currently being imported. Python creates a __file__ variable for itself when it is about to import a module.


Use this to get the path of the current file. It will resolve any symlinks in the path.

import os

file_path = os.path.realpath(__file__)

This works fine on my mac. It won't work from the Python interpreter (you need to be executing a Python file).


import os
print os.path.abspath(__file__)

7.2 of Dive Into Python: Finding the Path.

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)) 

The accepted solution for this will not work if you are planning to compile your scripts using py2exe. If you're planning to do so, this is the functional equivalent:

os.path.dirname(sys.argv[0])

Py2exe does not provide an __file__ variable. For reference: http://www.py2exe.org/index.cgi/Py2exeEnvironment