Can I use List view to get strings from file?

I need to define some locations in a file where certain markers might be. I started thinking I would use list.index, but soon found myself returning 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 correct Python. There should be a simpler solution since Python is good. Hunting around this site and the internet i came up with something a little better

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

      

I know this is too much information, but since I finished the final final nights last night, I thought it was Python and we want to be successful this summer - let's try to understand the list.

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 was that the item in position must be the item that is used to create the list. That is, if I had a string instead fileinput.lineno()

, I would have a non-empty list, but that's not a problem.

Can the above process be translated into list comprehension?

Using the answer, but setting it up for readability

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

      

0


a source to share


1 answer


How about this?



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

      

+8


a source







All Articles