7

I'm running code under Enthought Canopy to open and read a file. It keeps telling me IOError.

But I am pretty sure the text file name is right and it is in the same directory with the Python file, and the code works well in other IDEs like Python IDLE. Don't know what's wrong. Any suggestions?

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

fails with IOError: [Errno 2] No such file or directory: 'words.txt'

3
  • Make sure it's not 'words.txt.txt'. Commented May 31, 2013 at 0:59
  • is it present in the same directory as the python file ? Commented May 31, 2013 at 1:06
  • Thank you guys, punchagan's answer works for me! Commented May 31, 2013 at 1:34

2 Answers 2

17

UPDATE: The following hack is not required in Canopy versions 1.0.3 and greater. Right click inside the Python pane, and select Keep Directory Synced to Editor.

The working directory of the python shell, isn't synchronized with the editor open. So, your python shell's working directory is probably not the same as your python file. To change your shell's directory to your python file's directory:

  1. Open the python file in question.
  2. Right click inside the python pane and select the option "Change to Editor Directory"

Hope that helps.

The solution above is indeed correct. Unfortunately it is necessary even in the current version of Canopy - Version: 1.3.0 (64 bit)

Sign up to request clarification or add additional context in comments.

2 Comments

By default, in the ipython shell in Canopy, your working directory, where words.txt will be found, is in your user home directory. But your python file is probably somewhere else. In ipython, "pwd will usually "Print the Working Directory" and "cd xxx" will let you change the working directory.
In Canopy versions 1.0.3 and greater, right click inside the Python pane, and select Keep Directory Synced to Editor.
0

It is also possible to open a txt file when giving a complete path in parentheses, to change all \ with /

from:

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

to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.