Python: Write a list of tuples to a file

with open('daemons.txt', 'w') as fp:
    fp.write('\n'.join('%s %s' % x for x in mylist))

If you want to use str.format(), replace 2nd line with:

    fp.write('\n'.join('{} {}'.format(x[0],x[1]) for x in mylist))

open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))

import csv
with open(<path-to-file>, "w") as the_file:
    csv.register_dialect("custom", delimiter=" ", skipinitialspace=True)
    writer = csv.writer(the_file, dialect="custom")
    for tup in tuples:
        writer.write(tup)

The csv module is very powerful!

Tags:

Python