from xml.sax.saxutils import XMLGenerator import codecs with codecs.open('/tmp/test.txt', 'w', encoding='utf-8') as f: print("f", f) xml = XMLGenerator(f, 'utf-8') xml.startDocument()