Python: leer todas las líneas de archivos de texto en bucle
Quiero leer un archivo de texto enorme línea por línea (y detenerme si se encuentra una línea con "str"). ¿Cómo comprobar, si se alcanza file-end?
fn = 't.log'
f = open(fn, 'r')
while not _is_eof(f): ## how to check that end is reached?
s = f.readline()
print s
if "str" in s: break
3 answers
No hay necesidad de comprobar si hay EOF en python, simplemente haga:
with open('t.ini') as f:
for line in f:
print line
if 'str' in line:
break
Es una buena práctica utilizar la palabra clave
with
cuando se trata de archivo objeto. Esto tiene la ventaja de que el archivo se cierra correctamente después su suite termina, incluso si se plantea una excepción en el camino.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-30 14:23:27
Simplemente itera sobre cada línea en el archivo. Python comprueba automáticamente el final del archivo y cierra el archivo por usted (usando la sintaxis with
).
with open('fileName', 'r') as f:
for line in f:
if 'str' in line:
break
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-30 14:21:30
Hay situaciones en las que no se puede utilizar la (bastante convincente) estructura with... for...
. En ese caso, haga lo siguiente:
line = self.fo.readline()
if len(line) != 0:
if 'str' in line:
break
Esto funcionará porque el readline()
deja un carácter de nueva línea final, donde as EOF es solo una cadena vacía.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-13 16:17:09