skip item in list "for loop"

J

Jacob Rael

I am new to python and I love it. I am hacking a file. I want to not
print a line if it contains the word 'pmos4_highv'. I also don't want
to print the next line. The following code works but it "smells bad"
and just doesn't look right. I was reading about generators. If I was
using one, I could do a .next() after the match and get rid of the
flags. Any suggestions how I can improve this?


inPmos = False

inFile = sys.stdin
fileList = inFile.readlines()

for line in fileList:
line = line.rstrip()
# Remove PMOS definitions - typically two lines. Screwed if only
one and last inst.
if inPmos:
inPmos = False
continue
if 'pmos4_highv' in line:
inPmos = True
continue


jr
 
D

Diez B. Roggisch

Jacob said:
I am new to python and I love it. I am hacking a file. I want to not
print a line if it contains the word 'pmos4_highv'. I also don't want
to print the next line. The following code works but it "smells bad"
and just doesn't look right. I was reading about generators. If I was
using one, I could do a .next() after the match and get rid of the
flags. Any suggestions how I can improve this?

A generator certainly would be handy:

def read_lines(inFile):
fg = iter(inFile)
for line in fg:
if "pmos4_highv" in line:
fg.next()
else:
yield line



lines = """a
b
c
d
pmos4_highv
no no!
e
f
g""".split("\n")


for line in read_lines(lines):
print line


Diez
 
F

Felipe Almeida Lessa

Em Sex, 2006-04-14 às 20:33 +0200, Diez B. Roggisch escreveu:
def read_lines(inFile):
fg = iter(inFile)
for line in fg:
if "pmos4_highv" in line:
fg.next()
else:
yield line

Just be aware that the "fb.next()" line can raise an StopIteration
exception that would otherwise be caught by the for loop. If you have
any resources that need to be cleaned up, try...finally is you friend.
 
D

Diez B. Roggisch

Felipe said:
Em Sex, 2006-04-14 às 20:33 +0200, Diez B. Roggisch escreveu:

Just be aware that the "fb.next()" line can raise an StopIteration
exception that would otherwise be caught by the for loop. If you have
any resources that need to be cleaned up, try...finally is you friend.

Actually I did that on purpose - as the StopIteration would simply end
the generator. Any clean-up - well, if that was the scope of the
generator on could add it of course, but I'd do that on the same level
the file has been opened.

Regards,

Diez
 
J

Jacob Rael

Thanks for the suggestions.
The solution I liked most was to prevent the lines from appearing in
the first place!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top