2

I have a flat file in txt format seperated by space.

ID  Math    Eng Phy
A   70      75  77
B   56      79  80
C   90      89  56

I need to compare each number if its less than 70. What i am doing : I am able to store this file in dictionary but when i am comparing number getting :

"if int(m) < 70:ValueError: invalid literal for int() with base 10: 'Math' " 

error. Below is my code:

with open('student.txt','r') as file:
     rows = ( line.split('\t') for line in file )
     d = { row[0]:row[1:] for row in rows }
for l in d:
    print(l,d[l])
    for m in d[l]:
        if int(m) < 70:
           print(m)
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
Pankaj_Dwivedi
  • 565
  • 4
  • 15
  • 1
    `m` is not what you appear to think it is. try `print`ing it before the cast to `int` – Ma0 Feb 12 '18 at 16:20
  • try `print(m)` before you try to make it an `int`. You may find that you need to `strip` it of whitespace or something – Ben Feb 12 '18 at 16:20
  • 2
    You need to exclude your header line. – sco1 Feb 12 '18 at 16:20
  • Why do you suppose Python might be trying to convert the word "Math" to an integer? – kindall Feb 12 '18 at 16:23
  • 1
    I suggest you learn how to debug your own code. Read https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems for some tips to get started. Debugging will show that you are attempting to convert the word `"Math"` to an integer value. (As will carefully reading the error message.) – Code-Apprentice Feb 12 '18 at 16:26
  • @Ev.Kounis I am printing it before cast and checking its type(m),its str type. I am suppose to print numbers smaller than 70. – Pankaj_Dwivedi Feb 12 '18 at 16:36

2 Answers2

2

You need to skip the first line because it is the header:

next(rows)
d = { row[0]:row[1:] for row in rows }

Btw, rows is a generator so it is better not to exhaust it for allocating less memory:

with open('student.txt','r') as f:
    rows = ( line.split('\t') for line.strip() in f )
    next(rows)

    for l in rows:
        for m in l[1:]:
            if int(m) < 70:
                print(m)
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
0

The mistake you are doing is that you are including the header in your calculations. Doing that ultimately results in a int('Math') which of course fails and raises a ValueError. So do this instead:

with open('student.txt') as file:
    d = {x: y for x, *y in [row.split() for row in file.split('\n')][1:]}
    for k, v in d.items():
        print('{}\n\t{}'.format(k, '\n'.join([x for x in v if int(x)<70] or '-')))

Notice the [1:] slicing on the internal list-comprehension.

Ma0
  • 15,057
  • 4
  • 35
  • 65