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.
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.
__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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With