33

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 
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Adia
  • 1,171
  • 5
  • 16
  • 33

8 Answers8

65
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))
GHajba
  • 3,665
  • 5
  • 25
  • 35
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 3
    `str.format` is the new idiom for formatting strings: http://www.python.org/dev/peps/pep-3101/. Although I'm sure `%` will last for many many moons... =) – Katriel Sep 29 '10 at 09:38
  • 2
    That should be `fp.write('\n'.join('{} {}'.format(x[0],x[1]) for x in mylist)` and `fp` is a file object (opened for writing, I assume). Format does not seem to take a tuple as an argument or I am doing something wrong. – sup Nov 30 '13 at 02:13
  • @sup: http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists – Ignacio Vazquez-Abrams Nov 30 '13 at 02:27
  • Ah, I always wondered what that asterisk meant. So it is `fp.write('\n'.join('{} {}'.format(*x) for x in mylist)` – sup Nov 30 '13 at 09:16
  • 2
    looks like the str.format line is missing the last parentheses, should be `fp.write('\n'.join('{} {}'.format(x[0],x[1]) for x in mylist))` – zeroandone Jul 19 '19 at 03:18
21
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!

Katriel
  • 120,462
  • 19
  • 136
  • 170
5
open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))
stan
  • 321
  • 3
  • 3
2

Here is the third way that I came up with:

for number, letter in myList:
    of.write("\n".join(["%s %s" % (number, letter)]) + "\n")
H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Adia
  • 1,171
  • 5
  • 16
  • 33
  • you don't need to turn it into a list to pass to `join`. other then that, it's almost exactly like Ignacio's answer, so you should probably accept his by clicking the checkmark under the votecount next to his answer.. – aaronasterling Sep 29 '10 at 11:12
1

simply convert the tuple to string with str()

f=open("filename.txt","w+")
# in between code
f.write(str(tuple)+'/n')
# continue
Kara
  • 6,115
  • 16
  • 50
  • 57
Rohit Sohlot
  • 19
  • 1
  • 5
1

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  
0

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')
artem_vetkin
  • 455
  • 2
  • 5
  • 8
0

why not simply use a for loop and a f string?

my_list_of_tuples = [(8, 'rfa'), (8, 'acc-raid'), (7, 'rapidbase'), (7, 'rcts'), (7, 'tve-announce'), (5, 'mysql-im'), (5, 'telnetcpcd'), (5, 'etftp'), (5, 'http-alt')]
with open("myfile.txt", mode="w", encoding="utf-8") as file:
    for tup in my_list_of_tuples:
        file.write(f"{tup[0]} {tup[1]}\n")