Ashwini Chaudhary's solution is a lot better, consider my answer just as a backgrounder on what went wrong and why it went wrong, and the difference between opening/closing files inside or outside the loop.
File opens and closes should be paired, like here, the file is repeatedly opened, written and closed inside the loop:
for a in range(3): result = 'abcd' + a opener = open('file.txt', "a") print results opener.write(results) opener.close()
However, in many cases it's not a good idea to open and close files inside a loop due to the cost of opening and closing a file, so it may be better to open the file before the loop, write the file in the loop, and close it after the loop:
opener = open('file.txt', "a") for a in range(3): result = 'abcd' + a print results opener.write(results) opener.close()
Of course, when the file remains open, and the loop is lengthy, you risk losing data should the program crash, be interrupted or on a reboot of the computer. In these cases, forcing a flush to the operating system is in many cases a better alternative than repeatedly opening/closing the file:
opener = open('file.txt', "a") for a in range(3): result = 'abcd' + a print results opener.write(results) opener.flush() opener.close()