-1

1) I have a text file, inside has some key values that MAY occur many times ( for example '002' or '006' or '007'

2) I have written some code, to find the line number, for EACH time a specific occurrence of '002'is found

3) The code works, but the latest find will overwrite any previous one, so I end up with one in the end. So, I need to store EACH line number, where '002' is found, into a list.

4)It is killing me, I cannot seem to get the line numbers stored. Please help..

# this is my code that finds the line numbers where '002' occurs 

lookup2 = 'Issuer:    002'


with open("C:/Destin/help.txt") as myFile:
    for num2, line in enumerate(myFile, 1):
        if lookup2 in line:
            print ('found the last num2 at line:', num2)
            num2int = int(num2)

output

found the last num2 at line: 7 found the last num2 at line: 14

Process finished with exit code 0


#this is my problematic code

lookup2 = 'Issuer:    002'

my_list = [0, 0, 0, 0, 0, 0, 0]

i = 0
while i < len(my_list):
    with open("C:/Destin/help.txt") as myFile:
        for num2, line in enumerate(myFile, 1):
            if lookup2 in line:
                my_list[i] = mylist.append(num2)
                i = i + 1

print( my_list )

I simply need to store all the line numbers so that I can write some logic to split the data in the file based on where certain information is

JCole869
  • 3
  • 1
  • 2
    There's a couple of obvious issues with your code. First, you're mixing `my_list` and `mylist`, which is just a typo. But more importantly, you don't need to create the list with dummy values before adding the real values. Simply initialise with `my_list = []` and add found values with `my_list.append(num2)`. You can get rid of the indexing variable `i` and all the other stuff. Please read about the basics of lists in Python before proceeding, for example here https://developers.google.com/edu/python/lists – Grismar Aug 07 '19 at 00:44

1 Answers1

0

store the indexes in a dict of lists where the key is the thing you're looking for and the values are lists of indexes

from collections import defaultdict

d = defaultdict(list)

with open("C:/Destin/help.txt") as myFile:
for num2, line in enumerate(myFile, 1):
    if lookup2 in line:
        print ('found the last num2 at line:', num2)
        d[lookup2].append(int(num2))

you should end up with something like:

d = {
    "002": [7, 14]
}

this way you can actually keep track of multiple lookups or keys in one place in case you need it.

new-dev-123
  • 361
  • 1
  • 6