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

Tags: python
Question!

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)

print(regels)

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



Answers
  • 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

Code:

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

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

Output:

C:\Users\dinesh_pundkar\Desktop>python c.py
[1, 2, 3]
Max number is - 3
Line number is -  3

C:\Users\dinesh_pundkar\Desktop>


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)

print(regels)

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


print(max)
# Close file
b.close()
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