Matias Matias - 3 months ago 9
Python Question

Python: Write data to file (excel or txt) with field names

What is the best way (or what would you suggest) to do the following thing in Pyhton:

I run several simulations in Python and I want to store some results (each simulation in a new sheet, or new txt file).

Example:

for model in simmodels:
result = simulate(model)
speed = result["speed"]
distance = result["distance"]


"speed" and "distance" are numpy arrays (1column, 1000lines)

Now i want to store these results with the following structure:

1 column: 1 line "speed" 2-1001 lines --> result-array speed

2 column: 1 line "distance" 2-1001 lines --> result-array distance
etc.

I am new to Python and i found a lot of possibilities (structured arrays in numpy, lists, dictionaries, etc.). I am looking for a pretty simple, straight forward approach :).

Thank you very much for your help

Answer

Please check link - CSV Module

CSV files can be opened in Excel also.

Please check the below code :

import csv

speed = [10,20]
dist = [100,200]
f = open("out.csv", 'wb')
try:
    writer = csv.writer(f)
    writer.writerow( ('Speed','Distance') )
    for i in range(2):
        writer.writerow( (speed[i],dist[i]) )
finally:
    f.close()

Content of out.csv file :

Speed,Distance
10,100
20,200

Also, if you want exact excel format, you can set dialect as below:

writer = csv.writer(f,dialect='excel')

Please check dialect section in shared link for more info.

Finally can be use as :

import csv

f = open("out.csv", 'wb')
writer = csv.writer(f,dialect='excel')
writer.writerow( ('Speed','Distance') )
for model in simmodels:
   result = simulate(model)
   speed = result["speed"]
   distance = result["distance"]
   writer.writerow( (speed,distance) )
f.close()
Comments