How to find the longest line from a text file in Python

In this tutorial, we will learn how to find the longest line from a text file in Python with some easy examples. We would be using two ways-

  1. Using for loop.
  2. Using max() function.

Using for loop: find the longest line from a text file in Python

Before writing the code, create a text document or a file for the same. Then create two variables, one for storing maximum length i.e. max_length and the other for storing the line having the maximum length i.e. max_len_line. Now, open the file and start reading it line by line using for loop. For every line compare the length of the current line with the value of max_length. If the length of the current line is greater than the value of max_length then store the length of the current line in max_length and the current line in max_len_line.

After the whole file is read, we will get the line which is having the maximum length.

max_length = 0
max_len_line = ''
file = open("name.txt")
for line in file:
    if(len(line) > max_length):
        max_length = len(line)
        max_len_line = line
print(max_len_line)
        

To know more about File Handling and its functions in Python visit-

Python File Handling

For example-

Input-

Hey! 
Welcome to the programming world of Python.
Python is an amazing language.
It is used for scientific and numeric computing, creating desktops GUIs, software development and business applications.

Output-

It is used for scientific and numeric computing, creating desktops GUIs, software development and business applications.

Using max() function: get the longest line from a text file in Python

We can use the max() function to find the line having the longest length by providing len as key to the function.

print (max(open('name.txt'), key=len))

For the same example above we will run the code-

Input

Hey! 
Welcome to the programming world of Python.
Python is an amazing language.
It is used for scientific and numeric computing, creating desktop GUIs, software development and business applications.

Output-

It is used for scientific and numeric computing, creating desktops GUIs, software development and business applications.

 

2 responses to “How to find the longest line from a text file in Python”

  1. Abhinav Varshney says:

    Such a beautiful explanation…keep educating us by such amazing codes

  2. Rashi says:

    Thank you so much Abhinav Varshney for your feedback.

Leave a Reply

Your email address will not be published. Required fields are marked *