1

I am having issues with the open() function in Python 3.2.3. The following code works well using 2.7.3, but not with Python 3:

    file = open("text.txt", 'r')

In Python3, it gives me a standard IOError:

    IOError: [Errno 2] No such file or directory: 'text.txt'

Note that the text.txt file that is referenced is in the same directory as the python file.

Any ideas?

8
  • 1
    What doesn't work? Do you get an error message? If so, what? Commented Apr 18, 2012 at 16:45
  • How does it fail? Does it through a syntax error, IOError, or something else? Can you provide a stack trace. It's hard to decode the answer when we don't have anything to go on. Commented Apr 18, 2012 at 16:46
  • 2
    What does os.getcwd() return? Commented Apr 18, 2012 at 16:48
  • 1
    It has definitely something to do with current working directory. Commented Apr 18, 2012 at 16:52
  • 2
    Don't post the answer as an edit. Post it as an answer, and accept it after the time delay allows it. In this case, if you don't think the question will help anyone else, you can just delete the question. Commented Apr 18, 2012 at 17:03

3 Answers 3

3

The file name is not relative to the directory of the file, but your current working directory (which you can find out with os.getcwd()).

If you want to open a file whose name is relative to your Python file, you can use the magic variable __file__, like this:

import os.path
fn = os.path.join(os.path.dirname(__file__), 'text.txt')
with open(fn, 'r') as file:
   # Do something, like ...
   print(file.read())
Sign up to request clarification or add additional context in comments.

2 Comments

In Python 3, one should probably be using pathlib.Path, no? Then again I landed here trying to figure out why open() doesn't work on a Path...
This question is about python 3.2, where pathlib is not present yet. Why don't you ask your question?
0

You are trying to open a file in read mode, and this file has to exist.

Perhaps problem is that the file just doesn't exist in your python3 path and therefore the open command fails, but 'text.txt' exist on your python2.7 lib (or somewhere in python2.7 path) and this is why python is able to locate the file and open it.

You can just try this code (this will assure you the file exist since you create it):

f = open('text.txt','w')
f.close()
f.open('text.txt','r')

Comments

0

I was using Eclipse with Pydev, and had the text.txt file within the package instead of on the project level. To access a file within the package, you need to use:

 file = open("[package]/text.txt", 'r')

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.