Sort lines by length

EasyFile Handling Programs · 15 of 38

Write a Python program to sort the lines of a file by their length.

Advertisement
Output
x
short
medium line
a much longer line here

Approach

  1. sorted(lines, key=len).

Solution

Python
with open("story.txt", "w") as f:    f.write("medium line\nx\na much longer line here\nshort\n") with open("story.txt") as f:    lines = f.read().splitlines()for line in sorted(lines, key=len):    print(line)
Output
x
short
medium line
a much longer line here
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs