您的位置:首页 > 编程语言 > Python开发

Python Path Discussion

2015-06-06 22:05 676 查看
There are various ways to get the path of a module or package in python, such as through the module attritube __file__, __name__. Other ways including os.path.realpath(), or sys.argv[0], etc; However, it should be noted that all these approaches differs
in behavior greatly based on the specific use cases.

First we need to be clear on three concepts, current working directory, relative path and absolute path. Current directory, working directory or current working directory are actually three different names that refers to the same thing. A current directory
is a directory in which a user/program is working on at a given time. A director is a special type of file that contains a list of objects (also files). A relative path makes sense only when, another absolute path to which it is relative to, is specified.

Note 1: An absolute pathname, also referred to as an absolute path or afull path, is the location of afilesystem object (i.e., file, directory or link) relative to theroot
directory.

( Cited from http://www.linfo.org/absolute_pathname.html)
Note 2: A directory has two attribute that needs attention: the name of the directory and the path of the directory

1. __file__:

Use os.path.realpath(__file__) to return the abs path of the module being called

The value of __file__ attribute by itself:

Python 3.4: always absolute path, but when the __file__ is the attribute of a imported module, the abs path is formatted in Unix style ("/" instead of "\")

Python 2.7 Relative path and absolute path depending on the CWD

2. sys.argv[0]

Returns abs path when the cwd is not the directory of which the entry script is lanuched. Returns relative path when the cwdis the directory of which the entry script is lanuched

3.sys.path[0]

ALWAYS returns the abs path of the directory of the entry point script, no matter what the cwd is.

4. os.getcwd()

always returns the current working directory of the __main__ script, even if this method is called from an imported script.

This indicts that for all script in a python program, either __main__ or others, the current working directory is the cwd of the __main__ script.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: