Python Program to Find the Longest Line in a File
Beginner · File handling
This program finds the longest line in a text file, measured in characters, and prints it with its line number and length. It keeps the longest line seen so far and replaces it whenever a longer one turns up.
Program
The longest line is line 3 "Code is read more often than it is written" Length: 42 characters
How it works
longeststarts as an empty string, so the first line read is always longer and takes its place.line.rstrip("\n")removes the newline, so the length counts only the characters you can see.- Each line is compared with
len(longest), and a longer one replaces it, together with its line number. - If two lines tie for the longest,
>keeps the first one; use>=to keep the last one instead.
Other ways to write it
Using max() and min() with key=len
Longest line: Simple is better than complex Shortest line: Keep it short
key=len tells max() and min() to compare the lines by their length instead of alphabetically.
Longest word in the file
Longest word: Practice with 8 letters
split() with no argument splits at spaces and newlines alike, so it gives every word in the file, and the same max(..., key=len) finds the longest.
Try it yourself
Change the program to find the shortest line instead, starting with shortest set to the first line of the file.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Characters in a File
- Read a File Line by Line
- Find the Longest Word in a Sentence
- Count the Lines in a File
- Read a Text File and Separate Words with #
- Count Vowels, Consonants, Uppercase and Lowercase Characters in a Text File
- Copy Lines Without the Letter 'a' to Another File
- Search a Roll Number in a Binary File
- Update Marks in a Binary File
- Store and Search User IDs and Passwords in a CSV File
All Python programs · CBSE class 12 practical file · Python exercises