# credit to the Stack Overflow user in the source link from pprint import pprint # ... Build your object somehow ... with open('output.txt', 'wt') as out: pprint(your_object, stream=out)