Reading blank blank blank blank blank files

Asked

Viewed 1,852 times

1

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

3 answers

7

You can use rstrip() for that reason:

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 to 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 return the value of the string without whitespace. O if check whether the resulting value of the strip or rstrip is empty. If it is not, the line is added to the list, and if not, it is ignored.

NOTE: rstrip removes blank spaces on the right. strip removes both left and right.

Original answer in SOEN;

  • 1

    In the rstrip() has how to specify the character you want to remove, eg: linhas = [linha.rstrip("\n") for linha in f]

  • 1

    @interesting zekk! looks like the rtrim, ltrim and trim of php :D

  • That’s right, same as rtrim of PHP.

6

You can use the function str.splitlines():

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

   for linha in linhas:
       print (linha)

-2


arquivo = open("arquivo.txt", "r")
for linhas in arquivo:
    linhas = arquivo.read().splitlines()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.