tags:

views:

83

answers:

4

Hi everyone.

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 

thanks in advance

+4  A: 
fp.write('\n'.join('%s %s' % x for x in mylist))
Ignacio Vazquez-Abrams
+1 But you should explain what fp is.
Andrei Ciobanu
`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... =)
katrielalex
also, `str.format` takes 2/3 the time.
aaronasterling
+3  A: 
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!

katrielalex
+1 for `with`. `Csv` is nice but optional.
Manoj Govindan
A: 

Thanks guys. Here is the third way that I came up with:

for number, letter in myList:
    of.write("\n".join(["%s %s" % (number, letter)]) + "\n")
Adia
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
I did accept his answer:)
Adia
+1  A: 
open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))
stan