Reputation: 13
I'm new here (and also in python) so tell me if I do something wrong. I have a little (I think) problem: I have a list of sublists where all variables (x) are float:
tab=[[x11,x12,x13],[x21,x22,x23]]
And I wanto to write to the *txt file without brackets [] and separated by ";" like this:
x11;x12;x13
x21;x22;x23
I tried to do it like this: but i have no idea what should I do next.
tab=[[x11,x12,x13],[x21,x22,x23]]
result=open("result.txt","w")
result.write("\n".join(map(lambda x: str(x), tab)))
result.close()
A lot of thanks for everyone who will try to help me.
Upvotes: 0
Views: 1749
Reputation: 2888
You should use this:
result.write("\n".join([';'.join([str(x) for x in item]) for item in tab]))
Or, little simpler:
result.write("\n".join([';'.join(map(str, item)) for item in tab]))
Upvotes: 0
Reputation: 1123042
You can use the csv
module for this:
import csv
with open("result.txt", "wb") as result:
writer = csv.writer(result, delimiter=';')
writer.writerows(tab)
The csv.writer.writerows()
method takes a list of lists, and converts floating point values to strings for you.
Upvotes: 3