Python Programmer Logo Python Programmer Python Programmer Logo


Python Tricks: Finding the Largest Number in a Text File

Below are the two python files I used in this video and the actual video


The video files

File Download Date Modified
Get Max Num from File - Method 1 Download File 2 Mar 2024
Get Max Num from File - Method 2 Download File 2 Mar 2024

The actual code in each file

Get Max Num from File - Method 1


#Max num from file, method 1

#First, let's open and read from the file
file = open("nums.txt")
fileContents = file.readlines()

#The first methiod is using a for loop
#Nearly forgot the variable
maxNum = 0
thisLine = 0
for count, line in enumerate(fileContents):
    num = int(line.strip())
    if num > maxNum:
        maxNum = num
    #using this method, we can aslo output the line num
        thisLine = count

print("The maximum number is:",maxNum)
print("It is on line:",thisLine)

Get Max Num from File - Method 2


#Max num from file, method 2

#Now let's use the second method

#Opening and reading form the file once again
file = open("nums.txt")
fileContents = file.readlines()

#Now there is an in-built method called "max"

maxNum = max(fileContents)

print("The maximum number in the file is:",maxNum)

"""This method, although it is faster does have drawbacks
for exmample you can't output what line this number is on
in the file"""