CSVMasterXD
CSVMasterXD

Reputation: 21

Writing nested lists into a .txt file

Given a list of lists where each inner list consists of a string and a float, and an open file for writing, write the contents of each inner list as a line in the file. Each line of the file should be the string followed by the float separated by a comma. Close the file when done.

def write_avg(L, out_file):  
    '''(list, file) -> NoneType
    >>> L = [['a', 2.0], ['b', 3.0], ['c', 4.0]]  
    a, 2.0  
    b, 3.0  
    c, 4.0  
    '''
    L1 = []  
    L2 = []  
    myList = []    
    for item in L:  
        if item == str:  
            item.append(L1)  
        elif item == float:  
            item.append(L2)  
        else:  
            return "error"  
        myList.append(L1, L2)  
    out_file.writelines(myList)  

How do I add a list to each new line of a .txt document??

Upvotes: 2

Views: 7084

Answers (4)

oaugustopro
oaugustopro

Reputation: 790

You can use tabulate:

from tabulate import tabulate

with open(file, "a") as writedfile:
    writedfile.write(tabulate(my_list, headers=headers))

Upvotes: 1

Anton vBR
Anton vBR

Reputation: 18906

If you are working with Python and tables I recommend the pandas library. The output can be achieved in one row like this:

import pandas as pd

L = [['a', 2.0], ['b', 3.0], ['c', 4.0]] 

pd.DataFrame(L).to_csv("output.csv",index=False)

Upvotes: 1

neehari
neehari

Reputation: 2612

Try this:

lst = [['a', 2.0], ['b', 3.0], ['c', 4.0]]

filename = 'test.txt'

with open(filename, 'w') as f:
     for sublist in lst:
          line = "{}, {}\n".format(sublist[0], sublist[1])
          f.write(line)

The output written to the file:

a, 2.0
b, 3.0
c, 4.0

Upvotes: 0

zimmerrol
zimmerrol

Reputation: 4951

Using python list expression you can do something like this:

myList = ["{0}, {1}".format(x1, x2) for (x1, x2) in L]
with open('filename.txt', 'w') as out_file:
    out_file.writelines(myList)

This will create for

L = [['a', 2.0], ['b', 3.0], ['c', 4.0]]  

this output:

a, 2.0
b, 3.0
c, 4.0

Upvotes: 0

Related Questions