How to find largest number in file and see on which line it is

Tags: python

The file looks like this:

1, a b
2, c d
3, e f

my current code

b = open('file.txt', 'r')

c = b.readlines()
regels = len(c)


I got the numbers of lines but still need biggest number + on which line it is.

  • Read line
  • Split it on basis of comma
  • Append first element to temp list.

Once complete reading of file is done,

  • To get maximum number, just use max function on temp list.
  • Since file is read line by line sequentially and appending number from line to temp list, to get line number on which maximum number is present, just find the index of max number in temp list and increment it by one since list index starts with zero.

P.S : Check last three print statements


num_list = []
with open('master.csv','r')as fh:
    for line in fh.readlines():

print num_list
print "Max number is -" ,max(num_list)
print "Line number is - ", (num_list.index(max(num_list)))+1


[1, 2, 3]
Max number is - 3
Line number is -  3


So you are just looking to find the biggest number in the first column of the file? This should help

b = open('file.txt', 'r')

c = b.readlines()
regels = len(c)


max = 0
for line in b.readlines():
  num = int(line.split(",")[0])
  if (max < num):
    max = num 

# Close file
By : Alastair

None of the answers give you the line of the max number so I'll post some quick code and refine later

max_num = 0
line_count = 0
with open('file.txt', 'r') as infile:
    for line in infile:
        number = int(line.split(',')[0])
        if number > max_num:
             max_num = number
             line_num = line_count
        line_count += 1
print (max_num)
print (line_num)
By : roganjosh

This video can help you solving your question :)
By: admin