[Tutor] Working with lines from file and printing to another keeping sequential order
Kent Johnson
kent37 at tds.net
Sun Apr 26 16:55:36 CEST 2009
On Sat, Apr 25, 2009 at 2:11 PM, Dan Liang <danliang20 at gmail.com> wrote:
> Hi Bob and tutors,
>
> Thanks Bob for your response! currently I have the current code, but it does
> not work:
>
> ListLines= []
> for line in open('test.txt'):
> line = line.rstrip()
> ListLines.append(line)
This could be written with a list comprehension:
ListLines = [ line.rstrip() for line in open('test.txt') ]
>
> for i in range(len(ListLines)):
>
> if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and
> ListLines[i+1].endswith("no"):
> print ListLines[i], ListLines[i+1], ListLines[i+2]
> elif ListLines[i].endswith("yes") and ListLines[i+1].endswith("no"):
> print ListLines[i], ListLines[i+1]
> elif ListLines[i].endswith("yes"):
> print ListLines[i]
> elif ListLines[i].endswith("no"):
> continue
> else:
> break
You only need to test for ListLines[i].endswith('yes') once. Then you
could use a loop to test for lines ending with 'no'.
for i in range(len(ListLines)):
if not ListLines[i].endswith('yes'):
continue
for offset in (1, 2):
if i+offset < len(ListLines) and ListLines[i+offset].endswith('no'):
print ListLines[i+offset]
You could adapt the above for a variable number of 'no' lines with
something like
for offset in range(1, maxNo+1):
> I get the following error:
> Traceback (most recent call last):
> File "test.py", line 18, in <module>
> if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and
> ListLines[i+1].endswith("no"):
> IndexError: list index out of range
That is because you have a 'yes' line at the end of the file so the
check for 'no' tries to read past the end of ListLines. In my code the
test for i+offset < len(ListLines) will prevent that exception.
Kent
More information about the Tutor
mailing list