1
How do I avoid reading a blank line in a file, to any operating system, using the Python language?
1
How do I avoid reading a blank line in a file, to any operating system, using the Python language?
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;
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)
+1 is why I like python :D
-2
arquivo = open("arquivo.txt", "r")
for linhas in arquivo:
linhas = arquivo.read().splitlines()
Browser other questions tagged python filing-cabinet
You are not signed in. Login or sign up in order to post.
In the
rstrip()
has how to specify the character you want to remove, eg:linhas = [linha.rstrip("\n") for linha in f]
– stderr
@interesting zekk! looks like the
rtrim
,ltrim
andtrim
of php :D– Wallace Maxters
That’s right, same as
rtrim
of PHP.– stderr