+1 vote
in Python by

Can you please explain error ValueError: invalid literal for int() with base 10: ''

During 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. If that line is not empty it continues. However, I am getting this error:

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

It is reading the first line but can't convert it to an integer.

What can I do to fix this problem?

The code:

file_to_read = raw_input("Enter file name of tests (empty string to end program):")

try:

    infile = open(file_to_read, 'r')

    while file_to_read != " ":

        file_to_write = raw_input("Enter output file name (.csv will be appended to it):")

        file_to_write = file_to_write + ".csv"

        outfile = open(file_to_write, "w")

        readings = (infile.readline())

        print readings

        while readings != 0:

            global count

            readings = int(readings)

            minimum = (infile.readline())

            maximum = (infile.readline())

1 Answer

0 votes
by
Just for the record:

>>> int('55063.000000')

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

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

Needs to do it like

>>> int(float('55063.000000'))

55063.0

Has to be used!

The following are totally acceptable in python:

passing a string representation of an integer into int

passing a string representation of a float into float

passing a string representation of an integer into float

passing a float into int

passing an integer into float

But you get a ValueError if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, you can convert to a float first, then to an integer:

Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example

print("Hello")

print('Hello')
...