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
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.
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.
To convert a Python tuple to DataFrame, use the pd. DataFrame() constructor that accepts a tuple as an argument and it returns a DataFrame.
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)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With