Since you're not writing to the file until you have fetched all the courses, you can open the file here rather than opening it before the fetching logic.