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. 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())
The following are totally acceptable in python:
int
float
float
int
float
But you get a
ValueError
if you pass a string representation of a float intoint
, 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 anint
, as @katyhuff points out above, you can convert to a float first, then to an integer: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.
Just for the record:
Got me here...
Has to be used!
You've got a problem with this line:
This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.
Listen to everyone else's advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.
I was getting similar errors, turns out that the dataset had blank values which python could not convert to integer.
Pythonic way of iterating over a file and converting to int:
What you're trying to do is slightly more complicated, but still not straight-forward:
This way it processes 5 lines at the time. Use
h.next()
instead ofnext(h)
prior to Python 2.6.The reason you had
ValueError
is becauseint
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: