Editor

Longest Line in a File

#544 · File handling · Beginner · 30 XP · about 6 min

Write longest_line(filename) that reads the text file filename and returns its longest line, without the newline character at its end. Spaces count as characters.

If several lines share the greatest length, return the first of them. An empty file has no lines, so return ''.

Examples

If notes.txt holds:

short
the longest one
mid

then longest_line('notes.txt') returns 'the longest one'.

If tie.txt holds abc, xyz and ab on three lines, longest_line('tie.txt') returns 'abc', the first of the two longest lines.

Note

The last line of a file may or may not end with a newline, and the newline is never part of a line's length.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.