Transferred from: http://www.cnblogs.com/wind-wang/p/5822192.html
Python Gets the current path
Import Os,sys
Use sys.path[0], sys.argv[0], OS.GETCWD (), Os.path.abspath (__file__), Os.path.realpath (__file__)
Sys.path is a list of search paths that Python will look for in the module, Sys.path[0] and sys.argv[0] is one thing because Python automatically adds sys.argv[0] to Sys.path.
If you execute Python getpath\getpath.py in the C:\test directory, then OS.GETCWD () outputs "C:\test" and sys.path[0] outputs "C:\test\getpath".
If you compile the Python script as an executable file using the Py2exe module, the output of sys.path[0] will change:
If the dependent library is packaged as a zip file by default, then Sys.path[0] will output "C:\test\getpath\libarary.zip";
If the Zipfile=none parameter is specified in the setup.py, the dependent library will be packaged into the exe file, then sys.path[0] will output "C:\test\getpath\getpath.exe".
#!/bin/Env python#-*-Encoding=utf8-*-Import Os,sysif__name__=="__main__": Print"__file__=%s"%__file__ Print"Os.path.realpath (__file__) =%s"%Os.path.realpath (__file__) Print"Os.path.dirname (Os.path.realpath (__file__)) =%s"%Os.path.dirname (Os.path.realpath (__file__)) Print"Os.path.split (Os.path.realpath (__file__)) =%s"% Os.path.split (Os.path.realpath (__file__)) [0] Print"Os.path.abspath (__file__) =%s"%Os.path.abspath (__file__) Print"os.getcwd () =%s"%os.getcwd () print"sys.path[0]=%s"% sys.path[0] Print"sys.argv[0]=%s"% sys.argv[0] Output Result: D:\>python./python_test/test_path.py__file__=./python_test/Test_path.pyos.path.realpath (__file__)=D:\python_test\test_path.pyos.path.dirname (Os.path.realpath (__file__))=D:\python_testos.path.split (Os.path.realpath (__file__))=D:\python_testos.path.abspath (__file__)=D:\PYTHON_TEST\TEST_PATH.PYOS.GETCWD ()=d:sys.path[0]=d:\python_testsys.argv[0]=./python_test/test_path.py
OS.GETCWD () "D:\", which takes the starting execution directory
Sys.path[0] or sys.argv[0] "D:\python_test", which is the directory where the script was executed initially
Os.path.split (Os.path.realpath (__file__)) [0] "D:\python_test", which is the directory where __file__ files test_path.py
Get the current path correctly:
__FILE__ is the currently executing file
# Get the path to the current file __file__
Print "Os.path.realpath (__file__) =%s"% Os.path.realpath (__file__)
# Get the directory where the current file __file__ is located
Print "Os.path.dirname (Os.path.realpath (__file__)) =%s"% Os.path.dirname (Os.path.realpath (__file__))
# Get the directory where the current file __file__ is located
Print "Os.path.split (Os.path.realpath (__file__)) =%s"% Os.path.split (Os.path.realpath (__file__)) [0]
Python Gets the current path