Reading files without a blank line

0

How do I avoid reading a blank line in a file, for any operating system, using the Python language?

    
asked by anonymous 08.08.2016 / 01:58

2 answers

7

You can use rstrip() for this:

with open(filename) as f:
    #Todas as linhas, incluíndo as em branco
    lines = (line.rstrip() for line in f)
    #linhas sem espaço em branco
    lines = (line for line in lines if line)

You can save everything in a list, through the list comphresion:

with open(filename) as f:
    names_list = [line.strip() for line in f if line.strip()]

Note that in one example I used strip and another rstrip . The function strip or rstrip will return the value of the string without whitespace. The if will check if the value resulting from the strip or rstrip call is empty. If it is not, the line is added to the list, and if not, it is ignored.

NOTE : rstrip removes whitespace to the right. strip removes both left and right.

Original answer on SOH

08.08.2016 / 02:02
6

You can use the str.splitlines() function:

with open("arquivo.txt", "r") as f:
   linhas = f.read().splitlines()

   for linha in linhas:
       print (linha)
    
08.08.2016 / 02:02