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

dop*_*man 2 python

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

poem = 'poem.txt'

f = file(poem)
while True:
    line = f.readline()
    if len(line) == 0:
        break
    print line,
f.close()
Run Code Online (Sandbox Code Playgroud)

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

"Programming is fun When the work is done if you wanna make your work also fun: use Python!"
Run Code Online (Sandbox Code Playgroud)

命令行输出是这样的:

"No such file or directory: 'poem.txt'"
Run Code Online (Sandbox Code Playgroud)

poem.txt文件与文件位于同一文件夹中.py.这里出了什么问题?

Nic*_*son 7

我相信你并没有从与poem.txt相同的目录中运行python脚本.通过执行以下操作来验证这一点:

import os
print os.getcwd()
Run Code Online (Sandbox Code Playgroud)

在你的脚本中.

更新

好像我是对的.运行时:C:/Users/Python/filepractice.py当前工作目录是您运行它的目录,而不是filepractice.py所在的目录.

如果您在cmd.exe中执行此操作

c:
cd \Users\Python
python filepractice.py
Run Code Online (Sandbox Code Playgroud)

它可能会奏效.