How to check empty lines in python

 When importing or reading a text file, some of the lines may be blank and those empty lines can give unwanted result to the code.

Here is how to check empty lines in python by using "if" statement.

The text files have the hidden newline escape sequence (\n)  so use an "if" statement to exactly match this character only.


with open("stock_list.txt") as f:

    for line in f:

        if line != "\n": #skipping empty lines

            line = line.rstrip()

Comments

Popular Posts