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
rawandnetAsked:
Who is Participating?
 
NorieVBA ExpertCommented:
Try this.

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
     max_line = line

print max_line #result

Open in new window

1
 
aikimarkCommented:
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.
0
 
rawandnetAuthor Commented:
Straight forward and easy solution.  Thank you
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.