PyNEwbie
PyNEwbie

Reputation: 4940

Can I use a List Comprehension to get Line Indexes from a file?

I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was

count=0
docIndex=[]
for line in open('myfile.txt','r'):
    if 'mystring' in line:
        docIndex.append(count)
    count+=1

But this is Python right. There has to be a simpler solution since well it is Python. Hunting around this site and the web I came up with something slightly better

newDocIndex=[]
for line in fileinput.input('myfile',inplace=1):
    if 'mystring' in line:
    newDocIndex.append(fileinput.lineno())

I know this is too much info but since I finished grading finals last night I thought well-this is Python and we want to make some headway this summer-lets try a list comprehension

so I did this:

[fileinput.lineno() for line in fileinput.input('myfile',inplace=1) if 'mystring' in line]

and got an empty list. So I first guessed that the problem is that the item in the for has to be the item that is used to build the list. That is if I had line instead of fileinput.lineno() I would have had a non-empty list but that is not the issue.

Can the above process be reduced to a list comprehension?

Using the answer but adjusting it for readability

listOfLines=[lineNumb for lineNumb,dataLine in enumerate(open('myfile')) if 'mystring' in dataLine]

Upvotes: 0

Views: 1541

Answers (1)

sykloid
sykloid

Reputation: 101266

What about this?

[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]

Upvotes: 8

Related Questions