Reputation: 1
I'm having an issue where I'm trying to pull the elements out of a text file that has the format [a b c d e...] into a list, and using split() to do this. This seems to work perfectly when outside the while loop, and the printed variable displays
['2016-2017', '1', '1', '1', '4', '1', '2', '2', '1', '0', '1', '1', '3', '1', '5', '0', '3',
'2', '4', '4', '2', '4', '2', '0', '1', '0', '4', '3', '2', '2', '3', '4', '4', '1', '2',
'0', '2', '6', '7']
which is exactly what I want. However, when I try to do this in the while loop using split(), I get an infinite loop of empty lists. I've tried removing split() from the loop and that prints
2017-2018 2 1 1 3 0 3 4 1 4 0 1 0 1 1 1 5 2 1 3 5 2 1 4 1 2 2 1 1 2 4 3 2 1 1 2 0 1 5
for all lines in the file, but I want it to look like the first printed variable.
My code for reference:
with open(HOTSPUR, 'r') as infile:
goals_line = infile.readline().strip().split()
print(goals_line)
while goals_line != '':
goals_line = infile.readline().strip().split()
print(goals_line)
Upvotes: 0
Views: 296
Reputation: 177481
goals_line
is a list so will never compare to ''
. As you stated, you eventually get empty lists ([]
) so you could check for that. But a better solution is to loop through the lines of the file:
with open(HOTSPUR) as infile:
for line in infile:
goals_line = line.strip().split()
print(goals_line)
Upvotes: 4