I am attempting to open and write to a file at the end of some for loop I have. However,
I get a “output” undefined prompt. (See code below)
Am I not declaring what output is as the same time I open my file ‘output.txt’ in write mode?
for X in Y
....
output = open(output.txt, 'w')
output.writelines(lines)
output.close()
This should be working right? is my syntax wrong? Or must I declare output = open outside of the for loop?
Notes: Python 2.7.3
Answered: Thank you all, I was trying to open output.txt not ‘output.txt’ hence python couldn’t understand my declaration.
The filename
output.txtis a string, but you have not quoted it. So the undefinedoutputPython complains about is not the variable result of theopen()call, but rather the improperly quoted string inside theopen()call.It gets misinterpreted as some object called
openon which you are accessing a propertytxt.