How can I remove the
file = open(filename, "w")
If you're writing the file, you should specify
open(filename, "wb"). That way, you'll be writing in binary mode, and Python won't attempt to determine the correct newlines for the system you're on.