How do I avoid reading a blank line in a file, for any operating system, using the Python language?
How do I avoid reading a blank line in a file, for any operating system, using the Python language?
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
You can use the str.splitlines()
function:
with open("arquivo.txt", "r") as f:
linhas = f.read().splitlines()
for linha in linhas:
print (linha)