简体   繁体   中英

How to fetch line numbers for all 'if' 'else' and 'elif' positions in a python file

Example: Suppose, we have a.py file containing the below code snippet. How do we read and extract the positions of if-elif-else

If fisrtconditon:#line 1
    If sub-condition:#line2
       print(line no 3)
elif secnd_condn:#line 4
     Xyz..#line5
     Xyz..#line6
elif third condition:line7
     ...line 8
else:#line 9
    Some content #line10***

Output:

[1,4,7,9]

You can use the ast module.

import ast

with open('file.py') as f:
    tree = ast.parse(f.read())  # parse the file

for node in ast.walk(tree):  # walk the tree
    if isinstance(node, ast.If):  # if the node is an If (or an If-else)
        print('If at line', node.lineno)  # print the line number
        if node.orelse:  # if the node has an else
            if isinstance(node.orelse[0], ast.If):  # if the else is an If
                print('Elif at line', node.orelse[0].lineno)  # print the line number
            else:
                print('Else at line', node.orelse[0].lineno)  # print the line number

ast is part of the standard library, so there's no need to install anything. It stands for Abstract Syntax Tree, and it's a representation of the structure of your code. You can find more information in the ast module documentation .

A simple solution is to iterate over the lines of the file, using enumerate to help you get the line number:

with open("somefile.py") as f:
    for line_no, line in enumerate(f, start = 1):
        if line[:2] ==  "if" and (line[2].isspace() or line[2] == "("):
            print(line_no, "if")
        elif line[:4] == "elif" and (line[4].isspace() or line[4] == "("):
            print(line_no, "elif")
        elif line[:4] == "else" and (line[4].isspace() or line[4] == ":"):
            print(line_no, "else")

Assumptions : this program assumes that somefile.py has correct syntax. Moreover, if this if statement appears indented, for example, inside a function definition, it would not work. The question's specifications did not dictate this requirement.

This program

  • opens the file "somefile.py" for reading (the default mode of open );
  • iterates over the lines of the file, using enumerate to get an index; by default, indices will start from 0 but we specify the start parameter so that it starts from 1 ;
  • if the line starts with an if plus a (whitespace character or opening paren) or an elif plus a (whitespace character or opening paren) or an else plus a (colon : or a whitespace character), then we print the line number as well as the corresponding if , elif , or else .
  • as we exit the with block, Python closes the file for us.

Example


If somefile.py is

if condition:
    if condition:
        something
elif condition:
    something
    something
elif condition:
    something
else:
    something

then the above program outputs

1 if
4 elif
7 elif
9 else

one-liner:

indexes = [x+1 for x in range(len(content)) if any(x in ['if', 'elif', 'else'] for x in [list(content[x].lower().replace('#line',' ').replace(':',' ').split(' '))[0]])]

indexes:

[1, 4, 7, 9]

The snipped below should do it:)

#!/usr/bin/env python
# get_lines.py

def get_lines():
    lines = []
    with open('file.py') as f:
        f = f.readlines()
    for line in range(len(f)):
        if f[line].startswith(('if', 'elif', 'else')):
            lines.append(line + 1)
    return lines


if __name__ == '__main__':
    print(get_lines())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM