Home > Blockchain >  How to fix this: ValueError: invalid literal for int() with base 10: ''
How to fix this: ValueError: invalid literal for int() with base 10: ''

Time:02-28

I am working on a program that reads a file with numbers, representing the steps a user has made each day for an entire year, the program needs to count the number of days in the year that the user has made 10,000 steps or more and display the number of days with 10000 or more steps. This is what I have so far:

steps.txt contains 365 lines of numbers like:

1102
9236
10643
2376
6815
10394
3055
3750
4181
5452
10745
9896
255........

Code:

file = open("steps.txt", "r")
line = int(file.readline())  #Coverted to integer so can be compared to 10,000

total = 0
while line >= 10000:
    total  = line
print("The number of days with 10,000 or more steps are: ", total)

file.close()

but I am getting this error: ValueError: invalid literal for int() with base 10: '' How can I fix it? I appreciate all the help. Thanks.

CodePudding user response:

readline() would only read the first line from the given text file. If you want to read the entire file, then you should use readlines(). Note that this would read the entire file into memory.

The following code works for me

>>> file = open("steps.txt", 'r')
>>> lines = list(map(int,file.readlines()))
>>> count = sum(line>10000 for line in lines)

I'm unable to reproduce the error you got, I would suggest checking the file again, may be print file.readlines() before converting them to integer to make sure that file isn't empty.

CodePudding user response:

Maybe some lines are empty lines or there are spaces at the end of the unprocessed, you can try to use strip () to remove the spaces, and then determine whether the empty lines, in addition, there is a problem with the use of readline in your code, which can only read a line of content, and you did not update the value of the line in the while loop, you can refer to the following way:

total = 0

with open("steps.txt") as f:
    for line in f:
        item = line.strip()
        if item and item.isdigit():
            total  = int(item)

print("The number of days with 10,000 or more steps are: ", total)
  • Related