Skip to main content
 首页 » 编程设计

python之我需要在哪里放置我的 .py 文件

2025年05月04日12bjzhanghao

在“艰难地学习 Python”中,作者指出我们可以导入脚本而无需使用 python ex25.py。我们可以执行 import ex25 脚本将运行。

当我这样做时,我得到:

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

作者说它看起来像这样

Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import ex25 
>>> sentence = "All good things come to those who wait." 
>>> words = ex25.break_words(sentence) 
>>> words 
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.'] 
>>> sorted_words = ex25.sort_words(words) 
>>> sorted_words 
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who'] 
>>> ex25.print_first_word(words) 
All 
>>> ex25.print_last_word(words) 
wait. 
>>> wrods 
Traceback (most recent call last): 
File "<stdin>", line 1, in <module> 
NameError: name 'wrods' is not defined 
>>> words 
['good', 'things', 'come', 'to', 'those', 'who'] 
>>> ex25.print_first_word(sorted_words) 
All 
>>> ex25.print_last_word(sorted_words) 
who 
>>> sorted_words 

Python 似乎无法找到ex25。也许我需要将它放在 Python 27 目录中?但是,如果我需要将所有 .py 文件放在那里,我该如何保持一个干净的目录?

当我没有收到第一个挑战(找不到文件)时,我得到:

>>> import ex25 
>>>  

好像什么都没发生。

请您参考如下方法:

在您的系统配置中,您会发现一个名为 PythonPath 的变量(默认 C:\Python27)。从命令行运行 python 命令时,它将检查您的当前目录(默认 C:\Users\[Your Name])和 PythonPath 指定的目录。 如果你想运行你的程序,你需要:

  1. 使用 ie 切换到您的程序所在的文件夹。 cd 桌面
  2. 放入你的Python27文件夹

如果您使用的是 IDLE,则无需使用控制台,只需按 F5 即可运行程序。