7

I use Windows 7.

myfile = open("matedata.txt", "a+")
print myfile.readline()
myfile.write("1")
myfile.close()

And this doesn't work.

myfile.write("1")
IOError: [Errno 0] Error
8
  • How come i can't edit my post? Myfile is an empty file. myfile.readline() returns "nothing" Commented Nov 9, 2013 at 19:11
  • What happens if you change it to a file that doesn't exist? Commented Nov 9, 2013 at 19:16
  • What happens if you do not read from this file - just write? Commented Nov 9, 2013 at 19:16
  • This is probably unrelated to your error, but you should use a with statement to handle your open file, rather than explicitly closing it. Commented Nov 9, 2013 at 19:16
  • 5
    You're running windows, you opened the file in a+ mode, and did a read operation before a write operation. This makes windows unhappy for whatever reason. I remember there being a workaround if you really need to do this, but really just don't read and write in a+ mode. Commented Nov 9, 2013 at 19:19

1 Answer 1

-2

When you open a file with python, you need to specify the type of access you want (read, write or append):

  • a - for appending
  • r - for reading
  • w - for writing

the '+' means update/create new if doesn't exists.

you getting IOError because you open file and you try to do both reading and writing with the same FD(file discreptor)

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

2 Comments

Incorrect. Reading and writing is possible with the same file. See the documentation (docs.python.org/3/library/functions.html#open), which says that + does not mean to create a file, but instead it means to open a file for both reading and writing.
In addition to what Dietrich Epp said, if the file doesn't exists, 'w' mode will create it, no need for the use of '+'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.