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

前端 未结 18 1855
甜味超标
甜味超标 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:58

    your answer is throwing errors because of this line

    readings = int(readings)
    
    1. Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.
    0 讨论(0)
  • 2020-11-22 03:02

    This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling

    So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.

    0 讨论(0)
  • 2020-11-22 03:03
        readings = (infile.readline())
        print readings
        while readings != 0:
            global count
            readings = int(readings)
    

    There's a problem with that code. readings is a new line read from the file - it's a string. Therefore you should not compare it to 0. Further, you can't just convert it to an integer unless you're sure it's indeed one. For example, empty lines will produce errors here (as you've surely found out).

    And why do you need the global count? That's most certainly bad design in Python.

    0 讨论(0)
  • 2020-11-22 03:04

    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 the next line is read.

    Something like this should work:

    for line in infile:
        next_lines = []
        if line.strip():
            for i in xrange(4):
                try:
                    next_lines.append(infile.next())
                except StopIteration:
                    break
        # Do your calculation with "4 lines" here
    
    0 讨论(0)
  • 2020-11-22 03:05

    I had hard time figuring out the actual reason, it happens when we dont read properly from file. you need to open file and read with readlines() method as below:

    with open('/content/drive/pre-processed-users1.1.tsv') as f:
        file=f.readlines()
    

    It corrects the formatted output

    0 讨论(0)
  • 2020-11-22 03:06

    Please test this function (split()) on a simple file. I was facing the same issue and found that it was because split() was not written properly (exception handling).

    0 讨论(0)
提交回复
热议问题