'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 


Solution 1:[1]

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

Solution 2:[2]

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!

Solution 3:[3]

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

Solution 4:[4]

Here is the third way that I came up with:

for number, letter in myList:
    of.write("\n".join(["%s %s" % (number, letter)]) + "\n")

Solution 5:[5]

simply convert the tuple to string with str()

f=open("filename.txt","w+")
# in between code
f.write(str(tuple)+'/n')
# continue

Solution 6:[6]

For flexibility, for example; if some items in your list contain 3 items, others contain 4 items and others contain 2 items you can do this.

mylst = [(8, 'rfa'), (8, 'acc-raid','thrd-item'), (7, 'rapidbase','thrd-item','fourth-item'),(9, 'tryrt')]

# this function converts the integers to strings with a space at the end
def arrtostr(item):
    strr=''
    for b in item:
        strr+=str(b)+'   '
    return strr

# now write to your file
with open('list.txt','w+') as doc:
    for line in mylst:
        doc.write(arrtostr(line)+'\n')
    doc.close()

And the output in list.txt

8   rfa   
8   acc-raid   thrd-item   
7   rapidbase   thrd-item   fourth-item   
9   tryrt  

Solution 7:[7]

After adding f-strings in Python you can use this example:

mylst = [(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im')]
f = open('out.txt', mode='w+')
for elem in mylst:
    f.write(f'{elem}\n')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GHajba
Solution 2 Katriel
Solution 3 stan
Solution 4 H. Pauwelyn
Solution 5 Kara
Solution 6 leon koech
Solution 7 artem_vetkin