Skip to content
Advertisement

Python: Write a list of tuples to a file

How can I write the following list:

[(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im'), (5, 'telnetcpcd'), (5, 'etftp'), (5, 'http-alt')]

to a text file with two columns (8 rfa) and many rows, so that I have something like this:

8 rfa
8 acc-raid
7 rapidbase
7 rcts
7 tve-announce
5 mysql-im
5 telnetcpcd 

Advertisement

Answer

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))
Advertisement