24

I get an error when I try to open a file in Python. Here is my code :

>>> import os.path
>>> os.path.isfile('/path/to/file/t1.txt')
>>> True
>>> myfile = open('/path/to/file/t1.txt','w')
>>> myfile
>>> <open file '/path/to/file/t1.txt', mode 'w' at 0xb77a7338>
>>> myfile.readlines()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading

I also tried:

for line in myfile:
    print(line)

and I got the same error. Does anybody know why this error occurs?

2 Answers 2

47

You opened the file for writing by specifying the mode as 'w'; open the file for reading instead:

open(path, 'r')

'r' is the default, so it can be omitted. If you need to both read and write, use the + mode:

open(path, 'w+')

w+ opens the file for writing (truncates it to 0 bytes) but also lets you read from it. If you use r+ it is also opened for both reading and writing, but won't be truncated.

If you are to use a dual-mode such as r+ or w+, you need to familiarize yourself with the .seek() method too, as using both reading and writing operations will move the current position in the file and you'll most likely want to move that current file position explicitly between such operations.

See the documentation of the open() function for further details.

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

3 Comments

Also note that 'r' is the default mode and doesn't have to be given explicitly.
@delnan: I've made it explicit in the answer.
@MartijnPieters: Thank you, That was a simple mistake
1

Simple mistake if you think about it it. In your code you are doing:

myfile = open('/path/to/file/t1.txt','w')

Which specifies it is for writing, what you need to do is set this to r which is for read

myfile = open('/path/to/file/t1.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.