适用于IDLE但不适用于命令提示符

时间:2011-12-30 20:53:54

标签: python

此代码适用于IDLE,但不适用于命令行。为什么不同?

poem = 'poem.txt'

f = file(poem)
while True:
    line = f.readline()
    if len(line) == 0:
        break
    print line,
f.close()

poem.txt文件存在(它是一个字符串)。 shell输出是这样的:

"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文件位于同一文件夹中。这里出了什么问题?

1 个答案:

答案 0 :(得分: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

它可能会奏效。

相关问题