【问题标题】:Python file open() in Enthought Canopy fails with: "IOError No such file or directory"Enthought Canopy 中的 Python 文件 open() 失败并显示:“IOError No such file or directory”
【发布时间】:2013-05-26 17:46:26
【问题描述】:

我正在 Enthought Canopy 下运行代码来打开和读取文件。它一直告诉我 IOError。

但我很确定文本文件名是正确的,并且它与 Python 文件位于同一目录中,并且该代码在 Python IDLE 等其他 IDE 中运行良好。不知道怎么了。有什么建议吗?

inFile = open('words.txt', 'r')
words = inFile.read().split()

IOError: [Errno 2] No such file or directory: 'words.txt' 失败

【问题讨论】:

  • 确保不是'words.txt.txt'。
  • 它与python文件是否存在于同一目录中?
  • 谢谢你们,punchagan 的回答对我有用!

标签: python file-io enthought canopy working-directory


【解决方案1】:

更新:Canopy 1.0.3 及更高版本不需要以下 hack。在 Python 窗格内右键单击,然后选择 Keep Directory Synced to Editor。

python shell 的工作目录,与打开的编辑器不同步。因此,您的 python shell 的工作目录可能与您的 python 文件不同。要将 shell 的目录更改为 python 文件的目录:

  1. 打开有问题的 python 文件。
  2. 在 python 窗格中右键单击并选择“更改为编辑器目录”选项

希望对您有所帮助。

上面的解决方案确实是正确的。不幸的是,即使在当前版本的 Canopy 中也是必要的 - 版本:1.3.0(64 位)

【讨论】:

  • 默认情况下,在 Canopy 的 ipython shell 中,您的工作目录(将在其中找到 words.txt)位于您的用户主目录中。但是您的 python 文件可能在其他地方。在 ipython 中,"pwd 通常会"打印工作目录","cd xxx" 会让你改变工作目录。
  • 在 Canopy 1.0.3 及更高版本中,在 Python 窗格内右键单击,然后选择 Keep Directory Synced to Editor。
【解决方案2】:

在括号中给出完整路径时也可以打开一个txt文件,将所有\改为/

来自:

text=open('C:\Users\Korisnik\Desktop\abeceda.txt')

到:

text=open('C:/Users/Korisnik/Desktop/abeceda.txt')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-17
    • 2023-04-03
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多