Home > OS >  Please tell me how to find the maximum number in the file?
Please tell me how to find the maximum number in the file?

Time:12-13

Please tell me how to find the maximum number in the file, if the file contains one number in one line? Python

CodePudding user response:

If you have myfile.txt like that:

4
6
7
23
14

then this code

with open("myfile.txt", "r") as f:
    t = []
    for line in f:
        t.append(int(line))
    print(max(t))

will output 23.

I'm not sure this is what you want.

CodePudding user response:

def f_max(filepath):
    with open(filepath, 'r') as f:
        #The readlines() method returns a list of remaining lines of the entire file
        lines = f.readlines()
        #Built-in Function max() return largest item in an iterable
        max_number = max(lines)
        return max_number
  • Related