【问题标题】:Python ImportError- what is wrong here?Python ImportError - 这里有什么问题?
【发布时间】:2016-11-09 20:35:00
【问题描述】:

我是编程和 Python 的新手。我正在关注Learn Python the Hard Way 一书。 作为练习 25 的一部分,我编写了一个脚本:

def break_words(stuff):   
    """This function will break up words for us."""   
    words = stuff.split(' ')    
    return words        

def sort_words(words):    
    """Sorts the words."""    
    return sorted(words)        

def print_first_word(words):    
    """Prints the first words after popping it off."""    
    word = words.pop(0)    
    print word
        
def print_last_word(words):    
    """Prints the last word after popping it off."""    
    word = words.pop(-1)    
    print word    
    
def sort_sentence(sentence):    
    """Takes in a full sentence and returns the sorted words."""    
    words = break_words(sentence)    
    return sort_words(words)       

def print_first_and_last(sentence):    
    """Prints the first and last words of the sentence."""    
    words = break_words(sentence)    
    print_first_word(words)`

我把这个从 gedit 保存为

ex25.py

路径下

C:\Users\Brandon\Experiment\Python_ex

我运行的是 64 位 Windows 7。

当我从 python.exe 导入 ex25 时 我明白了:

> Traceback (most recent call last):
>  File "(stdin)", line 1, in `<module>`
> ImportError: No module named ex25

在 Computer\Properties\Advanced\Environment Variables 下我添加了系统变量:

Python 路径

C:\Python27

这没有帮助。 我做错了什么?

【问题讨论】:

    标签: python import module importerror


    【解决方案1】:

    C:\Users\Brandon\Experiment\Python_ex 不在您的系统路径中,因此 python 不知道您的 ex25 模块在哪里可以找到

    import sys
    sys.path.append(r'C:\Users\Brandon\Experiment\Python_ex')
    

    【讨论】:

    • 我得到:NameError: name 'sys' is not defined
    • 不可能是真的。 sysPython Standard Library 的一部分,并且始终“可导入”
    • 我还没有导入系统。太感谢了!你提供了我的解决方案。
    【解决方案2】:

    我也遇到了同样的问题。因为我的文件保存在 Desktop/mint/ex25.py 中。我首先通过命令 cd Desktop/mint 将目录更改为桌面。而不是按照推荐的方式运行。它会解决它。 想要回到旧目录使用命令 cd -.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2015-05-23
      • 2011-01-22
      • 2016-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多