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
your answer is throwing errors because of this line
readings = int(readings)
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.
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.
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
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
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).