在IDLE中可用,但在命令提示符中不可用
这段代码在IDLE里能正常运行,但在命令行里却不行。为什么会有这样的区别呢?
poem = 'poem.txt'
f = file(poem)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
这个poem.txt
文件是存在的(它是一个字符串)。在命令行的输出是这样的:
"Programming is fun When the work is done if you wanna make your work also fun: use Python!"
而在命令行的输出则是这样的:
"No such file or directory: 'poem.txt'"
这个poem.txt
文件和.py
文件在同一个文件夹里。到底出了什么问题呢?
2 个回答
-1
试着在同一个文件夹里打开一个命令提示符窗口,然后输入以下命令:
"cd [当前文件夹]",接着再输入"python [你的文件].py"
7
我觉得你没有在和poem.txt文件同一个文件夹里运行你的python脚本。你可以通过在你的脚本里加上:
import os
print os.getcwd()
来确认这一点。
更新
看来我说得没错。当你运行:C:/Users/Python/filepractice.py
时,当前的工作目录是你运行这个命令的地方,而不是filepractice.py所在的文件夹。
如果你在cmd.exe里这样做:
c:
cd \Users\Python
python filepractice.py
可能就会成功。