Reputation: 205
can someone explain the code How it works: I am not familiar with while loop
line = file.readline()
L1=[]
while line != '' and line != '\n':
line = line[:-1].split()
L1.append(line)
line = file.readline()
return L1
and can I do it with a for loop? Is it:
for line in file.readline():
if line !='' and line !='\n':
line = line[:-1].split()
L1.append(line)
return L1
Upvotes: 0
Views: 112
Reputation: 18850
Nearly. The first example will stop looping when it reads a line matching ''
or '\n'
. You could simplify it to this:
from itertools import takewhile
[x.strip() for x in takewhile(lambda x: x not in ['', '\n'], file.readlines())]
This will store every line of the file, until it finds a ''
or '\n
, in a new array.
Upvotes: 0
Reputation: 8587
'\n'
, stop.'\n'
, strip()
is better IMO), split by whitespace, then append list.And the problem with your for
loop is that it won't stop on empty or '\n'
Upvotes: 4
Reputation: 2155
First read this: http://wiki.python.org/moin/WhileLoop This will explain a while loop to you.
A while loop is a loop which will continue while the conditions are true,
x = 0
while x < 10:
print(x)
x = x + 1
print("finished")
will print out 0 1 2 3 4 5 6 7 8 9 finished
when x==10 the loop will end and the word 'finished' will be printed.
Upvotes: 1