Some Name Some Name - 2 months ago 27
Python Question

Biggest number in a text file

I have a text file with numbers and names in the following format:

129308123, Some Name
12390123, Some Other Name


I am trying to grab the biggest number in this textfile and also read on what line it is located. I tried multiple methods but none seem to be working for me. What am I doing wrong?

My code:

file_in = open('kaartnummers.txt', 'r')
regels = len(file_in.readlines())

smallestInt = 0

intList = [int(x) for x in file_in.readlines()]


number = max(intList)
laatsteregel = ''

string_format = 'Deze file telt {0} regels\n' \
'Het grootste kaartnummer is: {1} en dat staat op regel {2}'
result = string_format.format(regels, number, laatsteregel)
print(result)

Answer

To find the largest number in the file, split the line with split

file_in = open('kaartnummers.txt', 'r')

smallestInt = 0

intList = [int(x.split(",")[0]) for x in file_in.readlines()]
print(intList)
regels = len(intList)
number = max(intList)
laatsteregel = ''

string_format = 'Deze file telt {0} regels\n' \
                'Het grootste kaartnummer is: {1} en dat staat op regel {2}'
result = string_format.format(regels, number, laatsteregel)
print(result)

kaartnummers.txt

11, Bob
22, James
33, Nick
23, Steve
25, John
21, Ken

Output

python pyprog.py 
[11, 22, 33, 23, 25, 21]
Deze file telt 6 regels
Het grootste kaartnummer is: 33 en dat staat op regel 

To get the line number, you can use this code (remember it starts at 0)

print("line number " + str(intList.index(max(intList))))