Link to home
Start Free TrialLog in
Avatar of rawandnet
rawandnet

asked on

write a code to find biggest value and print the line output

How to write python code that would find a biggest value from a file and print the line that hold that big value

example:
file.txt
10 172.1.1.1
200 172.1.1.2
3  172.1.1.3

The script should loop through file.txt find and select number 200 and print 200 172.1.1.2 to a file.

I have the following, but it only print the first number 200

max_num = 0
with open('file.txt', 'r') as data: # use the with context so that the file closes gracefully
  for line in data.readlines(): # read the lines as a generator to be nice to my memory

    val = int(line.split()[0])
    if val > max_num: # logic
     max_num = val
print max_num #result
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or use the max() function
with open('c:\users\mark\downloads\Q_29099696.txt') as f:
    print max(f.readlines(),key=lambda d: int(d.split(' ')[0]))

Open in new window

Note: this is 2.7 code.  The print statement is a function in version 3.
Avatar of rawandnet
rawandnet

ASKER

Straight forward and easy solution.  Thank you