Writing a list of lists of arbitrary length to a file

I have a list of forms

lssample=[  [ [A,B],[C] ] ,[ [D],[E,F] ],[ [G,H],[I] ]]

      

What is the most efficient way to write this to a file in the form

A,B : C
D: E,F
G,H : I

      

Please note that lengths are arbitrary for subscriptions. The code below only writes a list in the form (with brackets). Is there a pythonic way to write this file to a file?

with open("output1.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(lssample)

      

+3


source to share


4 answers


It looks like a pretty simple format to just create your own script like:

In [2]: data = [[['A','B'], ['C']], [['D'],['E','F']], [['G','H'], ['I']]]

In [3]: import io

In [4]: with io.StringIO() as f:
    ...:     for record in data:
    ...:         left, right  = map(",".join, record)
    ...:         f.write(f"{left} : {right}\n")
    ...:     final = f.getvalue()
    ...:

In [5]: print(final)
A,B : C
D : E,F
G,H : I

      

Note. io.StringIO

is just a buffer in memory that acts like a file for the purpose of simple illustration. You would simply do:



with open("output1.txt", "w") as f:
    ...

      

And of course you don't need to final = f.getvalue()

. Also, I am using Python 3.6 f-strings. If you don't have that, you can use:

f.write("{} : {}".format(left, right)

      

+6


source


The following line is what you are looking for (add spaces around the colon if you like):

output = "\n".join(','.join(head) + ":" + ','.join(tail) \
                   for head, tail in lssample)
print(output)
#A,B:C
#D:E,F
#G,H:I

      



Just write it to a file.

+3


source


use join

,

fp = open('file_name','w')
txt = '\n'.join([','.join(i)+ ' : ' + ','.join(j) for i,j in lssample]) 
fp.write(txt)
fp.close()

      

Result:

In [10]: print txt
A,B : C
D : E,F
G,H : I

      

+3


source


You can also do it with print

and a little helper function for brevity (which also reduces name lookups):

with open('output.txt', 'w') as fout:
    fmt = ','.join
    for fst, snd in lssample:
        print(fmt(fst), ':', fmt(snd), file=fout)

      

+1


source







All Articles