Sort a csv with python from standard input
<p>This is my python script for sorting by column a csv file read from stdin:</p>

<pre><code>with  sys.stdin as csvfile:
  reader = csv.reader(csvfile, delimiter=',')
  sortedlist = sorted(reader, key=operator.itemgetter(2))
  for row in sortedlist:
     print(','.join(row)),
     print('\n'),
</code></pre>

<p>I run the command in order to sort by 3rd column(zero indexed is 2):</p>

<pre><code>./sorter1.py &lt; test.csv &gt; test_sorted.csv
</code></pre>

<p>and the sorted file test_sorted.csv is:</p>

<pre><code>31,53,101,122 
88,95,103,59 
66,58,104,50 
93,46,105,52 
88,88,118,107 
**115,57,31,34** 
110,87,36,63 
32,108,36,107 
75,35,57,35 
99,46,57,28 
41,35,67,59 
108,99,98,35 
36,66,98,60 
</code></pre>

<p>It is like sorted two files and merged it. Is it a matter of buffer size of the reader or a matter of sorted method? </p>

<p><strong>This sorts alphabetically not numerically</strong></p>

<blockquote>
  <p>This sorts alphabetically not numerically</p>
</blockquote>

<p>You'll have to <em>cast</em> the sort column values to integer in order to sort numerically. I have replaced the sort function with a <code>lambda</code> that includes the conversion to <code>int</code>:</p>

<pre><code>sortedlist = sorted(reader, key=lambda x: int(x[2]))
</code></pre>

python sorting csv