Sort input file according to first column, no delimiters but spaces
<p>I'm a Python beginner and trying to post process the a long txt file which is a list without delimiters, only spaces. I wanna sort it according to the first column. </p>

<p>The code compiles fine, but it only sorts my output file according to the very first value in the first column, but not according to the number itself. I also tried itemgetter operator without success.</p>

<p>I have tried this for hours now and hope anyone can help me. Why does my line split function not have the effect that I want?</p>

<pre><code>f = open("traj_nvt_20000000.txt","r+") 
lines = f.readlines() for line in f.readlines():
line = line.strip()
parts = line.split(" ")
lines = sorted(lines, key=lambda line: line[0])
with open('test123.txt', 'w') as text:
    text.writelines(lines)
</code></pre>

<p>An excerpt of the text file table that I want to sort:</p>

<pre><code>54 2 -9.5377 -4.02842 -7.51558 7
55 2 -9.6834 -4.88656 -7.29358 7
459 2 -8.76522 -8.30942 -10.144 58
50 1 -9.33774 -4.46175 -7.24097 7
56 2 -8.84618 -4.59922 -7.44773 7
462 2 -10.3377 -9.37008 -10.2265 58
460 2 -8.59323 -8.64832 -9.32914 58
457 1 -8.96511 -8.38283 -9.63619 58
461 2 -9.0727 -7.89321 -9.40869 58
369 1 -5.93643 -6.20083 -7.56102 47
504 2 -7.94033 -2.66938 -10.3925 63
371 2 -6.24752 -6.57434 -7.3023 47
</code></pre>

<p>Help is very much appreciated.</p>

<p>you have to sort as numerical, not alphanumerical, so convert your string to integer or float (I don't have all your data, I'm not sure if they're all integers):</p>

<pre><code>lines = sorted(lines, key=lambda line: float(line[0]))
</code></pre>

<p>but it would be even better to sort on all the values by returning a tuple of floats so if first values are equal, the rest can be used to discriminate:</p>

<pre><code>lines = sorted(lines, key=lambda line: [float(x) for x in line])
</code></pre>

<p>BTW your sample code is incorrect (there's a mix of readlines &amp; loops at the start which does not work). Here's a small test which works:</p>

<pre><code>f = open(r"U:\test.txt","r")  # sample file in the question
lines=[]
for line in f:
    lines.append(line.strip().split(" "))
f.close()

lines.sort(key=lambda line: [float(x) for x in line])
for l in lines:
    print(",".join(l))
</code></pre>

<p>result:</p>

<pre><code>50,1,-9.33774,-4.46175,-7.24097,7
54,2,-9.5377,-4.02842,-7.51558,7
55,2,-9.6834,-4.88656,-7.29358,7
56,2,-8.84618,-4.59922,-7.44773,7
369,1,-5.93643,-6.20083,-7.56102,47
371,2,-6.24752,-6.57434,-7.3023,47
457,1,-8.96511,-8.38283,-9.63619,58
459,2,-8.76522,-8.30942,-10.144,58
460,2,-8.59323,-8.64832,-9.32914,58
461,2,-9.0727,-7.89321,-9.40869,58
462,2,-10.3377,-9.37008,-10.2265,58
504,2,-7.94033,-2.66938,-10.3925,63
</code></pre>

python sorting split lines