Basement Dweller2
Basement Dweller2

Reputation: 61

Python highest integer in a file

I am working on writing a function that returns the highest integer number in a specified file. The files only contain numbers. I came up with the following code;

def max_num_in_file(filename):
    """DOCSTRING"""
    with open(filename, 'r') as file:
        return max(file.read())

When I test this with a text file that I created, it returns the highest digit in any of the lines in the file. I need it to return the overall highest number rather than a single digit.

Upvotes: 0

Views: 1849

Answers (5)

R.A.Munna
R.A.Munna

Reputation: 1709

You may also go through it.

def max_num_in_file(filename):
    """DOCSTRING"""
    with open(filename, 'r') as file:
        # read every line and converting into list
        ls =  [x.strip().split() for x in file.readlines()]
        return max(map(int, sum(ls, [])))
        # sum(ls,[]) is used for converting into a single list
        # map() is used for convert string to int

Upvotes: 0

akp
akp

Reputation: 637

d=f.read()
max(map(int,d.split())) #given that file contains only numbers separated by ' ' 

# if file has other characters as well
max(map(int,[i for i in d.split() if i.isdigit()]))

Upvotes: 0

plagiat0r
plagiat0r

Reputation: 1

You need to iterate the file object and convert each line to int(). If the file is very large, I would advise agains using readlines() as it will alocate a huge list into the memory. I'ts better to use an iterator to do the job, iterate one line at a time:

def max_num_in_a_file(filename):
    def line_iterator(filename):
        with open(filename) as f:
            for line in f:
                yield int(line)
    return max(line_iterator(filename))

Beware the script will thrown an Exception if any line in your file is not convertable to an int() object. You can protect your iterator for such case and just skips the line, as follows:

def max_num_in_a_file(filename):
    def line_iterator(filename):
        with open(filename) as f:
            for line in f:
                try:
                    num = int(line)
                except ValueError:
                    continue
                yield num
    return max(line_iterator(filename))

This function will work for a file with numbers and other data, and will just skips lines that are not convertible to int().

Upvotes: 0

Right leg
Right leg

Reputation: 16720

Assuming your file contains one number on each line:

with open(path, 'r') as file:
    m = max(file.readlines(), key=lambda x: int(x))

Then m holds as a string the greatest number of the file, and int(m) is the value you are looking for.

file.readlines() gives you a list whose elements are the lines of the file. The max built-in function takes an iterable (here, that list of lines), and an optional key argument. The key argument is how you want the elements to be compared.

The elements of my iterable are strings which I know represent integers. Therefore, I want them to be compared as integers. So my key is lambda x: int(x), which is an anonymous function that returns int(x) when fed x.


Now, why did max(file.read()) not work?

file.read() gives you the string corresponding to the whole content of the file. Then again, max compares the elements of the iterable it is passed, and returns the greatest one, according to the order relation defined on the elements' type(s). For strings (str instances), it is the lexicographical order.

So if your file contains only numbers, all characters are digits, and the greatest element is the character corresponding to the greatest digit. So max(file.read()) will most likely return '9' in most cases.

Upvotes: 1

L Selter
L Selter

Reputation: 352

As long as your file is clean and has no empty/non number lines:

def max_num_in_file(filename):
    """DOCSTRING"""
    with open(filename, 'r') as file:
        return max([int(_x.strip()) for _x in file.readlines()])

Upvotes: 0

Related Questions