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 to share