Editor

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

longest_line_in_file.py
# Make a sample file to work on
with open("quotes.txt", "w") as f:
f.write("Practice makes perfect\n")
f.write("Simple is better than complex\n")
f.write("Code is read more often than it is written\n")
f.write("Keep it short\n")
longest = ""
longest_number = 0
with open("quotes.txt", "r") as f:
for number, line in enumerate(f, start=1):
line = line.rstrip("\n") # do not count the newline
if len(line) > len(longest):
longest = line
longest_number = number
print("The longest line is line", longest_number)
print(f'"{longest}"')
print("Length:", len(longest), "characters")
Output
The longest line is line 3
"Code is read more often than it is written"
Length: 42 characters

How it works

  1. longest starts as an empty string, so the first line read is always longer and takes its place.
  2. line.rstrip("\n") removes the newline, so the length counts only the characters you can see.
  3. Each line is compared with len(longest), and a longer one replaces it, together with its line number.
  4. 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

Using max() and min() with key=len
# Make a sample file to work on
with open("quotes.txt", "w") as f:
f.write("Practice makes perfect\nSimple is better than complex\nKeep it short\n")
with open("quotes.txt", "r") as f:
lines = f.read().splitlines()
print("Longest line:", max(lines, key=len))
print("Shortest line:", min(lines, key=len))
Output
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 in the file
# Make a sample file to work on
with open("quotes.txt", "w") as f:
f.write("Practice makes perfect\nSimple is better than complex\n")
with open("quotes.txt", "r") as f:
words = f.read().split() # every word in the file
longest_word = max(words, key=len)
print("Longest word:", longest_word, "with", len(longest_word), "letters")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises