推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
MyLeoWind
V2EX  ›  Python

import os 和 import os.path 的效果有什么不同?

  •  
  •   MyLeoWind · Sep 9, 2015 via Android · 4315 views
    This topic created in 3900 days ago, the information mentioned may be changed or developed.
    5 replies    2015-09-10 00:23:39 +08:00
    aisk
        1
    aisk  
       Sep 9, 2015
    效果一样,这点是 os 模块做了 hack ,所以上面两种 import ,都可以用 `os.path.xxx` 。

    不做 hack 的模块,比如这样的结构:

    ```
    a
    ├── __init__.py
    └── b.py
    ```

    就只能 `import a.b` ,或者 `from a import b` 来访问 b 模块的内容,而不能只 `import a` 然后 `a.b.xxx`。
    MyLeoWind
        2
    MyLeoWind  
    OP
       Sep 9, 2015 via Android
    @aisk 感谢!
    julyclyde
        3
    julyclyde  
       Sep 9, 2015
    os.path 比较特殊:
    1 import os 后可以直接使用 os.path 这个不稀罕,因为 import os 的时候,它已经把 path 放到了自己的__all__里,作为 exported symbol 了
    2 可以直接 import os.path 但需要注意的是 os 并不是一个 package 。这里利用了 python 的两个漏洞: 1 它并不严格区分 package 和 module ,所以会先尝试 import os 然后再判断 os.path 是否成功加载; 2 为了让它以为 os.path 成功加载, os 在 sys.modules 里加入了一项名为 os.path 的元素,作弊

    另外,根据 os.path 的注释,正确的做法是 import os 然后使用 os.path ,而不是直接 import os.path (虽然标准库和文档也有 import os.path 的做法,但不提倡)
    PythonAnswer
        5
    PythonAnswer  
       Sep 10, 2015
    os.path 是个 hack

    win 下导入的是 ntpath.py

    # Module 'ntpath' -- common operations on WinNT/Win95 pathnames
    """Common pathname manipulations, WindowsNT/95 version.

    Instead of importing this module directly, import os and refer to this
    module as os.path.
    """

    *nix 下是 posixpath.py

    """Common operations on Posix pathnames.

    Instead of importing this module directly, import os and refer to
    this module as os.path. The "os.path" name is an alias for this
    module on Posix systems; on other systems (e.g. Mac, Windows ),
    os.path provides the same operations in a manner specific to that
    platform, and is an alias to another module (e.g. macpath, ntpath ).

    Some of this can actually be useful on non-Posix systems too, e.g.
    for manipulation of the pathname component of URLs.
    """
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5630 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 05:59 · PVG 13:59 · LAX 22:59 · JFK 01:59
    ♥ Do have faith in what you're doing.