How to Find the longest line from file in Python Program?
Python is known for its simplicity and the power of expressiveness. Python has very simple syntax.
For an instant, writing code 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 read 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 the 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))
open() is function to open text file. Set “len” as key to max function. It will find the longest line from file in Python Program.
And we are here to make you more awesome.
Note: Save the text file in the same folder as python program. Otherwise, you need to provide appropriate text file path in 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.