Script for sorting lines
<p>I have a file that has content as below</p>

<pre><code>hi  hello  123

cat  dog   456

     boy   456

Ind  us    90

     Can   67
</code></pre>

<p>I am trying to sort lines in this file to something like this</p>

<pre><code>     boy   456
     Can   67
hi  hello  123

cat  dog   456

Ind  us    90
</code></pre>

<p>My code:</p>

<pre><code>file = open("filename",'w')

column = []

for line in file:
    column.append(int(line.split()[0]))
column.sort()

file.close()
</code></pre>

<p>I didn't get desired output. </p>

<p>I am trying to sort elements based on first element of the row. If first element is empty that line should be printed first. Lines with first element of the row not empty should be printed later</p>

<p>Please help</p>

<p>File content</p>

<pre><code>hi  hello  123
cat  dog   456
     boy   456
Ind  us    90
     Can   67
</code></pre>

<p>Basically, use the <code>key</code> of the <code>sorted</code> function to sort based upon the length of the split string. </p>

<pre><code>with open("filename") as f:
    lines = f.read().splitlines()
lines = sorted(lines, key=lambda l: len(l.split()))
for line in lines:
    print(line)
</code></pre>

<p>Output</p>

<pre><code>     boy   456
     Can   67
hi  hello  123
cat  dog   456
Ind  us    90
</code></pre>

python python-3.x sorting