io – Python IOError: File not open for writing and global name w is not defined

io – Python IOError: File not open for writing and global name w is not defined

The problem is in the open() call in writeDoc() that file mode specification is not correct.

openfile = open(numbers.txt, w)
                               ^

The w needs to have (a pair of single or double) quotes around it, i.e.,

openfile = open(numbers.txt, w)
                                ^

To quote from the docs re file mode:

The first argument is a string containing the filename.
The second argument is another string containing a few characters
describing the way in which the file will be used.

Re: If I drop the w paremeter, I get this other error: ..IOError: File not open for writing

This is because if no file mode is specified the default value is read, which explains the message about the file not being open for writing, its been opened for reading.

See this Python doc for more information on Reading/Writing files and for the valid mode specifications.

It is possible to append data to a file but you are currently trying to set the option to write to the file, which will override an existing file.

The first argument is a string containing the filename. The second
argument is another string containing a few characters describing the
way in which the file will be used. mode can be r when the file will
only be read, w for only writing (an existing file with the same
name will be erased), and a opens the file for appending; any data
written to the file is automatically added to the end. r+ opens the
file for both reading and writing. The mode argument is optional; r
will be assumed if it’s omitted.

In addition, your implementation results in the open() method looking for a parameter declared as w. However, what you want is to pass the string value to indicate the append option, which is indicated by a encased in quotes.

openfile = open(numbers.txt, a) 

io – Python IOError: File not open for writing and global name w is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *