In a test file your code works, until it tries to open template.

Where in your code does the error occur?
can you post example file to demonstrate the problem