问题
I am new to programming and Python. I am following the Learn Python the Hard Way book. As a part of exercise 25, I wrote a script:
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)`
I saved this from gedit as
ex25.py
under the path
C:\Users\Brandon\Experiment\Python_ex
I am running 64-bit Windows 7.
When I go to import ex25 from python.exe I get:
> Traceback (most recent call last):
> File "(stdin)", line 1, in `<module>`
> ImportError: No module named ex25
Under Computer\Properties\Advanced\Environment Variables I added the System Variable:
PYTHONPATH
C:\Python27
That didn't help. What am I doing wrong?
回答1:
C:\Users\Brandon\Experiment\Python_ex
is not on your system path, thus python is not aware where your ex25
module can be found
import sys
sys.path.append(r'C:\Users\Brandon\Experiment\Python_ex')
回答2:
I just had the same problem. As my file was saved in Desktop/mint/ex25.py . I first changed the directory to desktop by command cd Desktop/mint. and than run the way it has been recommended. It will solve it. Want to go back to older directory use command cd -.
来源:https://stackoverflow.com/questions/6862214/python-importerror-what-is-wrong-here