Writing to file only once it's done