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
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