-1

I have a list/array called position[] and it is used to store the position line number of the string by using find(). The string is the abc.py which is a python file(I will include the abc.py below).

Question: how do find the string position of all def.

Objective: capture the line number of the first def and the second def and third etc and stored it in position[]

abc.py:

 #!C:\Python\Python39\python.exe
    # print ('Content-type: text/html\n\n')

def hello_step0():
    create()
    login()

def hello2_step1():
    delete()

def hello2_step2():
    delete()

What i did to find the first occurrence of def

position = [] 
with open("abc.py","r") as file:
    line = file.readlines()
    line = str(line)
    print(line.strip().find("def")) # output 102
    position.append(line.strip().find("def"))
Gerald
  • 69
  • 8
  • I think you meant ```line number``` and not ```index``` of ```def``` ? – Ram Jul 04 '21 at 09:59
  • yes i mean line number i will edit the word. thanks for the input. – Gerald Jul 04 '21 at 10:01
  • Does this answer your question? [Get Line Number of certain phrase in file Python](https://stackoverflow.com/questions/3961265/get-line-number-of-certain-phrase-in-file-python) – Tomerikoo Jul 04 '21 at 13:00

2 Answers2

1

Try str.startswith:

position = [] 

with open("abc.py") as f:
    for index, line in enumerate(f.readlines()):
        if line.strip().startswith('def'):
            position.append(index)

print(position) #[3, 7, 10] --> line starts with 0

# 0 --> #!C:\Python\Python39\python.exe
# 1--->    # print ('Content-type: text/html\n\n')
# 2-->
# 3-->def hello_step0():
#     create()

To start with 1, just replace:

for index, line in enumerate(f.readlines(), 1):
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Epsi95
  • 8,832
  • 1
  • 16
  • 34
1

The Below code will give append line numbers of lines that starts with def to position list.

position = []
with open('abc.py', 'r') as f:
    for i, val in enumerate(f.readlines()):
        if val.startswith('def'):
            position.append(i)

Output:

position = [3,7,10]
Ram
  • 4,724
  • 2
  • 14
  • 22