-2

I apologize but I searched and could not find an existing question/answer that solved this.

Simply put, I just need to take a list of numbers in a file and grab the largest number.I would typically use bash but i have a Python requirement.

I know how to open a file for reading and output the contents of the file but I can't get it to process the for loop output. Thank you in advance.

Here's the bash equivalent of what i need to do in python:

chrisk@kihei:~$ cat foo
214101721792
214101675361
214101684152
214101743134
214101718688
214101731297
214101715541
214101743273
214101722035
214101703116
214101696928
214101687776
chrisk@kihei:~$ sort foo | tail -1
214101743273
chrisk@kihei:~$
user1117603
  • 421
  • 2
  • 5
  • 13
  • Search for "python read file" and "python get max number" – pushkin Mar 16 '18 at 02:49
  • Possible duplicate of [Pythonic way to find maximum value and its index in a list?](https://stackoverflow.com/questions/6193498/pythonic-way-to-find-maximum-value-and-its-index-in-a-list) – ivan_pozdeev Mar 16 '18 at 02:49
  • Thank you.. getting this for some reason..Interpreter is Python 2.7.12 >>> sorted(map(int, open('foo')))[-1] Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'd2Z5O3e215JM130F\n' – user1117603 Mar 16 '18 at 02:57
  • @user1117603, the file you provided in the question did not include any non-numeric lines. Those cannot be converted to integers simply by bassing them to `int`. Perhaps you could show us a larger portion of your actual input data, so we may help you. – bla Mar 16 '18 at 03:05
  • @bla yeah there's a line feed character after each value '\n' and that's why it doesn't think it's an int. Trying to figure out how to strip it... any pointers would be great. Thanks. – user1117603 Mar 16 '18 at 03:55
  • I got it.. thank you for your help: int(sorted(map(int, open('foo')))[-1]) – user1117603 Mar 16 '18 at 03:59

1 Answers1

3
with open('foo') as f:
    max_num = max(int(i) for i in f)

print(max_num)
bla
  • 1,840
  • 1
  • 13
  • 17