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?
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to