Python: Write data to file (excel or txt) with field names
<p>What is the best way (or what would you suggest) to do the following thing in Pyhton:</p>

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

<p>Example:</p>

<pre><code>for model in simmodels:
   result = simulate(model)
   speed = result["speed"]
   distance = result["distance"]
</code></pre>

<p>"speed" and  "distance" are numpy arrays (1column, 1000lines)</p>

<p>Now i want to store these results with the following structure:</p>

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

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

<p>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 :).</p>

<p>Thank you very much for your help</p>

<p>Please check link - <a href="https://pymotw.com/2/csv/" rel="nofollow">CSV Module</a> </p>

<p>CSV files can be opened in Excel also.</p>

<p>Please check the below code :</p>

<pre><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()
</code></pre>

<p>Content of out.csv file :</p>

<pre><code>Speed,Distance
10,100
20,200
</code></pre>

<p>Also, if you want exact excel format, you can set dialect as below:</p>

<pre><code>writer = csv.writer(f,dialect='excel')
</code></pre>

<p>Please check dialect section in shared link for more info.</p>

<p>Finally can be use as :</p>

<pre><code>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()
</code></pre>

python export-to-excel