Counting Lines and numbering them

Another question.

This program counts and numbers every line in the code unless it has a hash tag or if the line is empty. I got it to number every line besides the hash tags. How can I stop it from counting empty lines?

  def main():

    file_Name = input('Enter file you would like to open: ')

    infile = open(file_Name, 'r')

    contents = infile.readlines()
    line_Number = 0
    for line in contents:
        if '#' in line:
            print(line)
            if line == '' or line == '\n':
                print(line)
        else:
            line_Number += 1 
            print(line_Number, line)

    infile.close()

main()

Upvotes: 1

Views: 221

Answers (2)

Lev Levitsky
Lev Levitsky

Reputation: 65791

You check if line == '' or line == '\n' inside the if clause for '#' in line, where it has no chance to be True. Basically, you need the if line == '' or line == '\n': line shifted to the left :)

Also, you can combine the two cases, since you perform the same actions:

if '#' in line or not line or line == '\n':
    print line

But actually, why would you need printing empty stings or '\n'?

Edit: If other cases such as line == '\t' should be treated the same way, it's the best to use Tim's advice and do: if '#' in line or not line.strip().

Upvotes: 3

Simeon Visser
Simeon Visser

Reputation: 122376

You can skip empty lines by adding the following to the beginning of your for loop:

if not line:
    continue

In Python, the empty string evaluates to the boolean value True. In case, that means empty lines are skipped because this if statement is only True when the string is empty.

The statement continue means that the code will continue at the next pass through the loop. It won't execute the code after that statement and this means your code that's counting the lines is skipped.

Upvotes: 0

Related Questions