Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Write a list of tuples to a file

Tags:

python

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  
like image 600
Adia Avatar asked Sep 29 '10 09:09

Adia


People also ask

How do you write a list of tuples to a text file in Python?

Given a list of tuples, you open a file in write mode. For each tuple in the list, you convert all of its elements into strings, join them by spaces to form the string, and write the string with a new line to the file. Then you close the file.

Can you write a tuple to a file in Python?

Solution: There are four simple ways to convert a list of tuples to a CSV file in Python. What is this? CSV: Import the csv module in Python, create a csv writer object, and write the list of tuples to the file in using the writerows() method on the writer object.

How do you convert a tuple to a data frame?

To convert a Python tuple to DataFrame, use the pd. DataFrame() constructor that accepts a tuple as an argument and it returns a DataFrame.


2 Answers

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) 
like image 110
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 08:09

Ignacio Vazquez-Abrams


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!

like image 39
Katriel Avatar answered Sep 29 '22 09:09

Katriel