[Tutor] Working with lines from file and printing to another keeping sequential order

bob gailer bgailer at gmail.com
Sat Apr 25 16:32:39 CEST 2009

Dan Liang wrote:
> Dear Tutors,
> I have a file from which I want to extract lines that end in certain 
> strings and print to a second file. More specifically, I want to:
> 1) iterate over each line in the file, and if it ends in "yes", print it.
> 2) move to the line following the one described in #1 above, and if it 
> ends in, "no" print it.
> 3) move to third line, and if it ends in "no", print it.
> 4) move to fourth line, and if it ends in "no" discard it, but if it 
> ends in "yes" repeat 1, 2, and 3 above.
> 5) move to fifth line, and if it ends in "no" discard it, but if it 
> ends in "yes" repeat 1, 2, 3, and 4 above, and so on.
> The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file 
> in such a way that keeps the order of the lines in output. An 
> abstraction away from this so that any ratio of "yes" to "no" lines 
> could be printed while keeping the order of the original lines would 
> be great. 

Please show us what code you have written, and in what way it fails to 
meet your expectations.

Your specification is IMHO a nice piece of pseudocode which could 
translate to Python fairly easily!

What do we do at steps 4ff if the line does not end in "yes" or "no"?

If you have not written any code make a stab at it. You could start by 
asking "how in Python does one":
open a file?
iterate (loop)?
get the next line from a file?
test for equality?
examine the end of a string?

Bob Gailer
Chapel Hill NC

More information about the Tutor mailing list