print odd numbers of lines from tekst WITHOUT space between lines
Peter Otten
__peter__ at web.de
Sat Feb 18 15:41:54 EST 2017
TTaglo wrote:
> i = 1
> f = open ('rosalind_ini5(1).txt')
> for line in f.readlines():
> if i % 2 == 0:
> print line
> i += 1
>
>
> How do i get output without breaks between the lines?
I'm late to the show, but here are a few unsolicited remarks to your code.
(1) The best way to open a file is
with open(filename) as f:
# use the file
# at this point the file is closed without the need to invoke
# f.close() explicitly
(2) The readlines() method reads the complete file into a list. This can
become a problem if the file is large. It is better to iterate over the file
directly:
for line in f:
# use the line
(3) If you read the file into a list you can get all odd lines with
for odd_line in f.readlines()[1::2]:
# use the odd line
(4) If you follow my advice from (2) and want to avoid the in-memory list
there's an equivalent itertools.islice() function that you can use like
this:
import itertools
for odd_line in itertools.islice(f, 1, None, 2):
# use the odd line
(5) sys.stdout.write() was already mentioned, but there is also a
sys.stdout.writelines() meathod which takes a sequence of strings. With that
your code may become
import itertools
import sys
with open('rosalind_ini5(1).txt') as f:
sys.stdout.writelines(itertools.islice(f, 1, None, 2))
More information about the Python-list
mailing list