Search code examples
python-3.xexport-to-csvxlsxwriter

Output each element of list of list from Python to .csv file


I am trying to write each list-element from a list of list in Python to a .csv file, but I keep getting the strings whose letters are space-separated for some unknown reasons. A sample code is below:

import xlsxwriter

S = [[1, 7, 8, 0], [4, 5, 7, 3], [2, 9, 10, 11, 6]]

with open('S_N=6.csv', 'wt') as graph:

    graphWriter = csv.writer(graph, delimiter = ' ')

    for x in range(len(S)):

      graphWriter.writerow('set S' + str(x+1)  + ':=')

My intended output (notice that the index i in S[i] can be computed as (the last element in each list/3) + 1)

set S[1] = 1 7 8
set S[2] = 4 5 7
set S[3] = 2 9 10 11

Can someone please help me with this problem? Any inputs would be greatly appreciated.


Solution

  • Your output file is not CSV. It's makes no sense to use a CSV writer to generate it. It's just a bunch of lines, so write just a bunch of lines.

    S = [[1, 7, 8, 0], [4, 5, 7, 3], [2, 9, 10, 11, 6]]
    
    with open('S_N=6.csv', 'w') as fp:
        for x in S:
            *items, idx = x
            idx = int(idx / 3 + 1)
            items = ' '.join(map(str, items))
            fp.write(f'set S[{idx}] = {items}\n')
    
    • *items, idx = x assigns all but the last list element in x to items, and the last element to idx.
    • idx / 3 + 1 returns a float, i.e. 1.0 and so on. It must be converted to int explicitly.
    • f'...' is a format string, you can use Python expressions in curly braces inside.

    This writes:

    set S[1] = 1 7 8
    set S[2] = 4 5 7
    set S[3] = 2 9 10 11
    

    Since format strings can contain complex expressions, you could write it as follows, if you really wanted to:

    for x in S:
        *items, idx = x
        fp.write(f'set S[{int(idx / 3 + 1)}] = {' '.join(map(str, items))}\n')