You have the call to readlines
into a loop, but this is not its intended use,
because readlines
ingests the whole of the file at once, returning you a LIST
of newline terminated strings.
You may want to save such a list and operate on it
list_of_lines = open(filename).readlines() # no need for closing, python will do it for you
odd = 1
for line in list_of_lines:
if odd : print(line, end='')
odd = 1-odd
Two remarks:
odd
is alternating between 1
(hence true when argument of an if
) or 0
(hence false when argument of an if
),
- the optional argument
end=''
to the print
function is required because each line in list_of_lines
is terminated by a new line character, if you omit the optional argument the print
function will output a SECOND new line character at the end of each line.
Coming back to your code, you can fix its behavior using a
f.seek(0)
before the loop to rewind the file to its beginning position and using the
f.readline()
(look, it's NOT readline**S**
) method inside the loop,
but rest assured that proceding like this is. let's say, a bit unconventional...
Eventually, it is possible to do everything you want with a one-liner
print(''.join(open(filename).readlines()[::2]))
that uses the slice notation for lists and the string method .join()