【问题标题】:Python module import not workingPython模块导入不起作用
【发布时间】:2017-10-17 09:39:15
【问题描述】:

我收到以下代码的错误:

from os import getcwd
os.getcwd()

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
os.getcwd()
NameError: name 'os' is not defined

有人知道为什么导入这种方式不起作用吗?

【问题讨论】:

    标签: python python-import getcwd


    【解决方案1】:

    有两种可能。第一个是每次调用函数时导入模块并命名模块:

    import os
    print os.getcwd()
    

    或者你可以直接导入模块的方法,调用时不用给模块命名:

    from os import getcwd
    print getcwd()
    

    【讨论】:

    • 谢谢你的作品。我想每当我使用以这种方式导入的函数时,我都必须省略模块名称,对吧?
    【解决方案2】:
    from os import getcwd
    print getcwd()
    

    当您只导入getcwd 而不是os 时,os.getcwd 怎么能工作

    【讨论】:

    • 我现在明白了。我只是 python 的新手,所以仍然在一些基础知识上苦苦挣扎
    • @West 如果你做import os,那么你可以做. 部分
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2015-04-30
    • 2023-02-09
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多