-4

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?

James Lee
  • 3
  • 3
  • 1
    You are calling `int` on the string `'-'`, which will throw an error. – juanpa.arrivillaga Apr 20 '18 at 06:05
  • Why don't you post a [mcve] including what value `item` has at the error? – user202729 Apr 20 '18 at 06:07
  • Why is the string '-' being created? the file should only have 1 number per line, and I am converting each string in string_list to it's int in num_list – James Lee Apr 20 '18 at 06:11
  • Show the contents of file? – Austin Apr 20 '18 at 06:13
  • I don't have access to it unfortunately. – James Lee Apr 20 '18 at 06:21
  • The error couldn't be any clearer. Have you tried `print(item)` before `num_list.append(int(item))`, or at least *Google* the error? – CristiFati Apr 20 '18 at 06:24
  • Possible duplicate of [ValueError: invalid literal for int() with base 10: ''](https://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10) – CristiFati Apr 20 '18 at 06:25
  • @CristiFati I don't understand how the answer you linked fixes my error, so I posted this question – James Lee Apr 20 '18 at 06:51
  • Yes, the context is different, but the error is the same, your're trying to convert to int a string that isn't formatted as an int. Some answers (not the accepted one) mention `try` / `except`, and also how to use `.strip()` instead of `[0:-1]` – CristiFati Apr 20 '18 at 08:01

2 Answers2

0

It seems that you are trying to convert to int simply a dash (or minus sign), but no number...

int('-2')  # No error: -2
int('-')   # Your error

Could it be that you are reading from an Excel file that has the accounting (or similar) formatting on (in which 0s are formatted as dashes)?

WillMonge
  • 1,005
  • 8
  • 19
0

You can avoid this by using try/except block e.g.:

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))
    infile.close()

    num_list = []
    for item in string_list:
        try:
            num_list.append(int(item))
        except ValueError:
            print('Got ValueError for item --> ', item)
    return max(num_list)

e.g. file content:

1
2
3
4
6
6-
6
-
-

The result of max_num_in_file()

Got ValueError for item -->  6-
Got ValueError for item -->  -
Got ValueError for item -->  - 
6

This try/except block will prevent program not to stop and print what was wrong. This way you can implement other functions to clean your data and etc...

simkusr
  • 770
  • 2
  • 11
  • 20