Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to select every other line from a text file?

837 views
Skip to first unread message

Rff

unread,
Oct 13, 2014, 1:39:03 PM10/13/14
to
Hi,
I have a text file. Now it is required to select every other line of that text to
generate a new text file. I have read through Python grammar, but still lack the
idea at the beginning of the task. Could you tell me some methods to get this?


Thanks,

Chris Angelico

unread,
Oct 13, 2014, 1:46:52 PM10/13/14
to pytho...@python.org
There are a few ways of doing this. I'm guessing this is probably a
homework assignment, so I won't give you the code as-is, but here are
a few ideas:

1) Iterate over the file (line by line), alternating between writing
the line out and not writing the line out.
2) Read the file into a list of lines, then slice the list with a step
of 2, and write those lines out.
3) Iterate over the file, but also consume an extra line at the top or
bottom of the loop.
4) Read the entire file into a string, then abuse regular expressions
violently until they do what you want.

And there are other ways, too. Show us some code and we can help you
with it; but at the moment, this is fairly open-ended.

ChrisA

John Gordon

unread,
Oct 13, 2014, 1:48:57 PM10/13/14
to
Initialize a counter variable to zero. (Or one, depending if you want to
select odd or even lines.)

Each time you read a line from the file, add one to the counter.

If the counter is odd, process the line; otherwise use the 'continue'
statement to start the loop over and read another line.

--
John Gordon Imagine what it must be like for a real medical doctor to
gor...@panix.com watch 'House', or a real serial killer to watch 'Dexter'.

Gary Herron

unread,
Oct 13, 2014, 1:57:24 PM10/13/14
to pytho...@python.org
Read in your lines, keeping a counter as you go.  "Select" those lines whose counter is even (or odd -- you didn't say which you wanted).

So now some questions for you:
  • Do you know how to open a file and read in all the lines?
  • Do you know how to count as you do so?
  • Do you know how to test for evenness?   (Use count%2 will be zero for even count values.)
  • Do you know how to write lines to an output file?
Gary Herron

Mark Lawrence

unread,
Oct 13, 2014, 2:03:11 PM10/13/14
to pytho...@python.org
On 13/10/2014 18:48, John Gordon wrote:
> In <3be64ca8-d2e7-493a...@googlegroups.com> Rff <rw...@avnera.com> writes:
>
>> Hi,
>> I have a text file. Now it is required to select every other line of that
>> text to generate a new text file. I have read through Python grammar, but
>> still lack the idea at the beginning of the task. Could you tell me some
>> methods to get this?
>
> Initialize a counter variable to zero. (Or one, depending if you want to
> select odd or even lines.)
>
> Each time you read a line from the file, add one to the counter.
>
> If the counter is odd, process the line; otherwise use the 'continue'
> statement to start the loop over and read another line.
>

Why bother to initialise a counter when you can get the enumerate
function to do all the work for you?

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

emile

unread,
Oct 13, 2014, 2:12:46 PM10/13/14
to pytho...@python.org
On 10/13/2014 11:02 AM, Mark Lawrence wrote:

> Why bother to initialise a counter when you can get the enumerate
> function to do all the work for you?

I see it as a question of addressing the audience.

Emile



Joel Goldstick

unread,
Oct 13, 2014, 2:46:11 PM10/13/14
to pytho...@python.org
I don't agree with the idea of using a counter. Its not pythonic, and
I'm assuming the OP is just starting to learn python.

Not apropos to the OP, but what came up in my mind was to write a
generator function that returns every other line. This would separate
the reading from the writing code.

>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list



--
Joel Goldstick
http://joelgoldstick.com

Grant Edwards

unread,
Oct 13, 2014, 3:05:09 PM10/13/14
to
On 2014-10-13, Chris Angelico <ros...@gmail.com> wrote:
> On Tue, Oct 14, 2014 at 4:38 AM, Rff <rw...@avnera.com> wrote:
>> I have a text file. Now it is required to select every other line of that text to
>> generate a new text file. I have read through Python grammar, but still lack the
>> idea at the beginning of the task. Could you tell me some methods to get this?
>>
>
> There are a few ways of doing this. I'm guessing this is probably a
> homework assignment, so I won't give you the code as-is, but here are
> a few ideas:
>
> 1) Iterate over the file (line by line), alternating between writing
> the line out and not writing the line out.
>
> 2) Read the file into a list of lines, then slice the list with a step
> of 2, and write those lines out.
>
> 3) Iterate over the file, but also consume an extra line at the top or
> bottom of the loop.
>
> 4) Read the entire file into a string, then abuse regular expressions
> violently until they do what you want.

I'd vote for #3. Or write a generator that does something similar
when given a parameter object that implements readline().

Of course, the _real_ answer is:

os.system("sed -n 'g;n;p' '%s'" % filename)

;)

--
Grant Edwards grant.b.edwards Yow! Didn't I buy a 1951
at Packard from you last March
gmail.com in Cairo?

Tim Chase

unread,
Oct 13, 2014, 3:09:20 PM10/13/14
to Rff, pytho...@python.org
You could force a re-read from the file each line:

with open("x.txt") as f:
for line in f:
do_something(line)
next(f) # discard/consume the next line

Or, if you have it read into memory already, you could use slicing
with a stride of 2:

with open("x.txt") as f:
data = f.readlines()
interesting = data[::2] # start with the 1st line
# interesting = data[1::2] # start with the 2nd line

Or, if the file was large and you didn't want to have it all in
memory at the same time, you could use itertools.islice()

from itertools import islice
with open("x.txt") as f:
interesting = islice(f, 0, None, 2) # start with 1st line
#interesting = islice(f, 1, None, 2) # start with 2nd line

Note that in the last one, you get an iterator back, so you'd have to
either turn it into a list or iterate over it.

-tkc



Tim Chase

unread,
Oct 13, 2014, 3:45:17 PM10/13/14
to Joel Goldstick, pytho...@python.org
On 2014-10-13 14:45, Joel Goldstick wrote:
> Not apropos to the OP, but what came up in my mind was to write a
> generator function that returns every other line. This would
> separate the reading from the writing code.

You mean like

offset = 0 # or 1 if you prefer
for line in itertools.islice(source_iter, offset, None, 2):
do_something(line)

?

-tkc


emile

unread,
Oct 13, 2014, 4:02:11 PM10/13/14
to pytho...@python.org
On 10/13/2014 12:12 PM, Tim Chase wrote:

> You mean like
>
> offset = 0 # or 1 if you prefer
> for line in itertools.islice(source_iter, offset, None, 2):
> do_something(line)


I certainly did. Learning the python standard library is different from
learning python and each in its own time.

Emile




Denis McMahon

unread,
Oct 13, 2014, 7:54:25 PM10/13/14
to
So this could be written as an algorithm something like:

1/ open the input file
2/ open the output file
3/ while there are lines to read from the input file
3/1/ read a line from the input file
3/2/ if I should output this line
3/2/1/ write line to output file
4/ close the input file
5/ close the output file

Or in several other ways, and once you have an algorithm, you can start
coding it (or implementing it in the programming language of your choice,
whichever form of words best pleases your perfesser).

--
Denis McMahon, denismf...@gmail.com

Dan Stromberg

unread,
Oct 13, 2014, 8:35:12 PM10/13/14
to Rff, Python List
Perhaps something like:
http://stromberg.dnsalias.org/svn/every-nth/trunk

It uses zip and itertools.cycle.

It's CPython 3.x though - if you need 2.x, you'd probably use xrange
instead of range, and izip instead of zip.
0 new messages