Python: writing a text file with a lot of variables
<p>I need to create (from Python code) a text file with in each line some 50 variables, separated by comm's. I take the canonical way to be
    output.write ("{},{},{},{},{},{},{},{},{},{}, ... \n".format(v,v,v,v,...
But that will be hard to read and difficult to maintain with such a lot of variables. Any other suggestions? I have thought of using the csv module, after all what I am writing is (kind of) a csv file, but thought I'd hear around for other suggestions first.</p>

<h2>Using lists</h2>

<p>When reaching a handful of variables that are related to each other, it is common to use a <code>list</code> or a <code>dict</code>. If you create a list:</p>

<pre><code>myrow = []
myrow.append(v1)
...
</code></pre>

<p>This also allows for easier looping over each value. Once you have done that you can easily concatenate it to a string:</p>

<pre><code>f.write(','.join(myrow))
</code></pre>

<p>In case your row might contain any commas (or whatever you use as a delimiter) you must ensure escaping. In this case a CSV modules helps:</p>

<pre><code>import csv
with open('myfile.csv', 'w') as f:
  fw = csv.writer(f)
  fw.writerow(myrow)   # where myrow is a list
</code></pre>

<h2>Using dicts</h2>

<p>Some people prefer to add additional structure, e.g.:</p>

<pre><code>myrow = {}
myrow['speed'] = speed_value
myrow['some_other_row'] = other_value

import csv
with open('myfile.csv', 'w') as f:
  fw = csv.writer(f)
  fw.writerow(myrow)
</code></pre>

python csv file-writing