【问题标题】:works in IDLE but not the command prompt适用于 IDLE 但不适用于命令提示符
【发布时间】:2021-08-21 02:13:00
【问题描述】:

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

【问题讨论】:

  • 你可以试试用./poem.txt代替poem.txt
  • 你是如何从命令行调用你的python脚本的,你能提供一个例子吗?
  • @EknathIyer——这不会导致指针在目录中向上移动一个文件夹吗?
  • @DRH--C:/Users/Python/filepractice.py Enter
  • @codeninja:“这不会导致指针向上移动一个文件夹”?编号. 是 Linux 的“此目录”。 .. 是父目录。

标签: python


【解决方案1】:

我相信您没有从与poem.txt 所在的同一目录中运行python 脚本。通过输入来验证这一点:

import os
print os.getcwd()

在你的脚本中。

更新

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

如果你在 cmd.exe 中这样做

c:
cd \Users\Python
python filepractice.py

它可能会起作用。

【讨论】:

  • 没问题...很高兴为您提供帮助。 :)
【解决方案2】:

尝试在同一目录中打开命令提示符窗口,输入命令:

“cd [当前目录]”然后是“python [yourfile].py”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多