Python Path Discussion

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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值