2011-07-28 80 views
0

我是编程和Python的新手。我正在关注Learn Python the Hard Way的书。 锻炼25的一部分,我写了一个脚本:Python ImportError-这里有什么问题?

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)` 

我路径

C:\Users\Brandon\Experiment\Python_ex

下保存这个从gedit中作为

ex25.py

我运行64位Windows 7.

当我从python.exe 导入ex25时,我得到:

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

在电脑\属性\高级\环境变量我加了系统变量:

PYTHONPATH

C:\Python27

没有帮助。 我在做什么错?

回答

5

C:\Users\Brandon\Experiment\Python_ex是不是你的系统路径,从而蟒蛇不知道在您的ex25模块可以发现

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

我得到:NameError:名称'sys'未定义 –

+0

不能为真。 ['sys'](http://docs.python.org/library/sys.html)是['Python Standard Library']的一部分(http://docs.python.org/library/index.html)并始终“可导入” – Nemoden

+1

我还没有导入sys。非常感谢!你提供了我的解决方案。 –

0

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