I am trying to write code that reads a file (containing 1 number per line) and returns the largest int value found in the file (as an int)
This is my code:
def max_num_in_file(filename):
"""
returns the largest integer found in file, as an integer.
"""
infile = open(filename, "r")
lines = infile.readlines()
string_list = []
for line in lines:
string_list.append((line[0:-1]))
infile.close()
num_list = []
for item in string_list:
num_list.append(int(item))
return max(num_list)
However with one particular file (in which the max int is -2) I am getting this error:
Traceback (most recent call last):
File "source.py", line 20, in <module>
answer = max_num_in_file('max_num_in_file_test_04.txt')
File "source.py", line 13, in max_num_in_file
num_list.append(int(item))
ValueError: invalid literal for int() with base 10: '-'
Can anyone diagnose this error for me?