Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to write a little procedure that write (append would be even better) a line in a file with Python, like this:

def getNewNum(nlist):
    newNum = ''
    for i in nlist:
        newNum += i+' ' 
    return newNum

def writeDoc(st):
    openfile = open("numbers.txt", w)
    openfile.write(st)

newLine =  ["44", "299", "300"]

writeDoc(getNewNum(newLine))

But when I run this, I get the error:

openfile = open("numbers.txt", w)
NameError: global name 'w' is not defined

If I drop the "w" paremeter, I get this other error:

line 9, in writeDoc
    openfile.write(st)
IOError: File not open for writing

I'm following exactly (I hope) what is here.

The same occurs when I try to append the new line. How can I fix that?

like image 771
craftApprentice Avatar asked Jul 03 '12 18:07

craftApprentice


2 Answers

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 'r'ead, which explains the message about the file not being open for "writing", it's been opened for "reading".

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

like image 187
Levon Avatar answered Oct 04 '22 22:10

Levon


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") 
like image 20
Robert Avatar answered Oct 04 '22 21:10

Robert