ValueError: invalid literal for int() with base 10: ''

前端 未结 18 2097
甜味超标
甜味超标 2020-11-22 02:06

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then t

18条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 02:56

    Pythonic way of iterating over a file and converting to int:

    for line in open(fname):
       if line.strip():           # line contains eol character(s)
           n = int(line)          # assuming single integer on each line
    

    What you're trying to do is slightly more complicated, but still not straight-forward:

    h = open(fname)
    for line in h:
        if line.strip():
            [int(next(h).strip()) for _ in range(4)]     # list of integers
    

    This way it processes 5 lines at the time. Use h.next() instead of next(h) prior to Python 2.6.

    The reason you had ValueError is because int cannot convert an empty string to the integer. In this case you'd need to either check the content of the string before conversion, or except an error:

    try:
       int('')
    except ValueError:
       pass      # or whatever
    

提交回复
热议问题