I keep getting the "print() on closed filehandle" error in my code when I try to print to it. The output that I want works perfectly when printed to the terminal but does not work when printed to my desired output file. Can anyone help figure out what the problem is?

http://pastebin.com/qGzAe6Y2