You are opening the file for each string in text without closing it, which is probably what causes your error (which you didn't mention).

Use with and don't bother with closing the file (and also don't name the file reference file, as it will shadow Python's built-in file). Also note that you will need to use 'a' as the opening mode so you always appending to the file instead of truncating it: