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>

<p>If you can sort of your variables, you could use locals().</p>

<p>for example:</p>

<p>I set three variables:</p>

<pre><code>var1 = 'xx'
var2 = 'yy'
var3 = 'zz'
</code></pre>

<p>and I can sort of them by sorted().</p>

<pre><code>def sort(x):
    if len(x) != 4:
        return '99'
    else:
        return x[-1]

sortVars = sorted(locals(), key=sort)
</code></pre>

<p>Then, using <strong><code>for</code></strong> combination them.</p>

<pre><code>result = ''

for i in sortVars[:3]:
    result += locals()[i]

print(result)
</code></pre>

python csv file-writing