¿El mejor método para leer archivos delimitados de nueva línea en Python y descartar las nuevas líneas?


Estoy tratando de determinar la mejor manera de manejar la eliminación de nuevas líneas al leer en archivos delimitados por nuevas líneas en Python.

Lo que se me ocurrió es el siguiente código, incluir código desechable para probar.

import os

def getfile(filename,results):
   f = open(filename)
   filecontents = f.readlines()
   for line in filecontents:
     foo = line.strip('\n')
     results.append(foo)
   return results

blahblah = []

getfile('/tmp/foo',blahblah)

for x in blahblah:
    print x

Sugerencias?

Author: solarce, 2009-02-13

7 answers

lines = open(filename).read().splitlines()
 180
Author: Curt Hagenlocher,
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-01-16 00:03:44

Aquí hay un generador que hace lo que solicitó. En este caso, usar rstrip es suficiente y un poco más rápido que strip.

lines = (line.rstrip('\n') for line in open(filename))

Sin embargo, lo más probable es que desee usar esto para deshacerse de los espacios en blanco al final también.

lines = (line.rstrip() for line in open(filename))
 20
Author: TimoLinna,
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
2009-02-13 08:35:46
for line in file('/tmp/foo'):
    print line.strip('\n')
 8
Author: David Z,
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
2009-02-13 06:36:08

¿Qué piensas de este enfoque?

with open(filename) as data:
    datalines = (line.rstrip('\r\n') for line in data)
    for line in datalines:
        ...do something awesome...

La expresión del generador evita cargar el archivo completo en la memoria y with asegura el cierre del archivo

 8
Author: Paweł Prażak,
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-09-21 10:48:51

Simplemente use expresiones del generador:

blahblah = (l.rstrip() for l in open(filename))
for x in blahblah:
    print x

También quiero aconsejarle que no lea todo el archivo en memoriaoping el bucle sobre generadores es mucho más eficiente en grandes conjuntos de datos.

 4
Author: ,
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
2009-02-14 07:43:58

Yo uso esto

def cleaned( aFile ):
    for line in aFile:
        yield line.strip()

Entonces puedo hacer cosas como esta.

lines = list( cleaned( open("file","r") ) )

O, puedo extender limpiado con funciones adicionales para, por ejemplo, soltar líneas en blanco u omitir líneas de comentario o lo que sea.

 3
Author: S.Lott,
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
2009-02-13 11:07:27

Lo haría así:

f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l
 2
Author: S.Lott,
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
2009-02-13 11:06:06