How to Find the longest line from file in Python Program?

How to Find the longest line from file in Python Program?

Do you have a task to find the longest line from the text file?

You can write a simple Python script to do this job.

Python is known for its simplicity and the power of expressiveness. Python has a very simple syntax.

For an instant, writing code on how to find the longest line from file in Java or C/CPP needs lots of effort. Create the object of the file. Open a file using an object with reading privilege. Call a function to read a file. Manipulate every line from file and compare its length of every line.

It is very much simple to find the longest line from file in Python. It is possible to get output with a single line of code.

Here you go to find the longest line from file in Python Program.

Create a text file and put some texts in it. Save it as “testFile.txt” file.

Hello,
CSEStack is portal for CS programmer. 
You are a programmer, awesome! 
And we are here to make you more awesome.

Code to find the longest line from file in Python:

Write simple code as below to find the longest line from file in Python and save it as .py file.

#Finding the longest line in a file:
print (max(open('testFile.txt'), key=len))

The open() is a function to open a text file. Set “len” as key to max function. It will find the longest line from file in Python Program.

Output:

And we are here to make you more awesome.

Read more detail about file handling in Python.

Note: Save the text file in the same folder as python program. Otherwise, you need to provide an appropriate text file path in the Python program.

If you are getting rid of using command console to run python file, how if I introduce you with one of the awesome IDE for python. Read this Complete Tutorial to setup Python With Pycharm.

Happy Coding!

Leave a Reply

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