The issue wasn't with creating the output file, so I've readded the code that did that part correctly.