I have about 50 GB of text file and I am checking the first few characters each line and writing those to other files specified for that beginning text.
For example.
Use the with statement, it automatically closes the files for you, do all the operations inside the with block, so it'll keep the files open for you and will close the files once you're out of the with block.
with open(inputfile)as f1, open('dog.txt','a') as f2,open('cat.txt') as f3:
#do something here
EDIT:
If you know all the possible filenames to be used before the compilation of your code then using with is a better option and if you don't then you should use your approach but instead of closing the file you can flush the data to the file using writefile1.flush()