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?
The problem is in the open() call in
writeDoc()that file mode specification is not correct.The
wneeds to have (a pair of single or double) quotes around it, i.e.,To quote from the docs re file mode:
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.