Omita el primer par de líneas mientras lee líneas en un archivo Python


Quiero saltarme las primeras 17 líneas mientras leo un archivo de texto.

Digamos que el archivo se ve así:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
good stuff

Solo quiero lo bueno. Lo que estoy haciendo es mucho más complicado, pero esta es la parte con la que estoy teniendo problemas.

Author: Jason Sundram, 2012-03-06

8 answers

Use un corte, como a continuación:

with open('yourfile.txt') as f:
    lines_after_17 = f.readlines()[17:]

Si el archivo es demasiado grande para cargarlo en memoria:

with open('yourfile.txt') as f:
    for _ in range(17):
        next(f)
    for line in f:
        # do stuff
 82
Author: wim,
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
2018-05-15 05:49:42

Uso itertools.islice, comenzando en el índice 17. Se saltará automáticamente las 17 primeras líneas.

import itertools
with open('file.txt') as f:
    for line in itertools.islice(f, 17, None):  # start=17, stop=None
        # process lines
 21
Author: Ismail Badawi,
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
2018-04-14 20:47:36
for line in dropwhile(isBadLine, lines):
    # process as you see fit

Demo completa:

from itertools import *

def isBadLine(line):
    return line=='0'

with open(...) as f:
    for line in dropwhile(isBadLine, f):
        # process as you see fit

Ventajas: Esto es fácilmente extensible a los casos en los que las líneas de prefijo son más complicadas que "0" (pero no interdependientes).

 2
Author: ninjagecko,
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
2012-05-06 23:14:33

Esta solución me ayudó a omitir el número de líneas especificadas por la variable linetostart. Obtienes el índice (int) y la línea (cadena) si quieres hacer un seguimiento de ellos también. En su caso, sustituya linetostart por 18, o asigne 18 a la variable linetostart.

f = open("file.txt", 'r')
for i, line in enumerate(f, linetostart):
    #Your code
 2
Author: Wilder,
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
2016-04-30 19:55:40

Aquí hay un método para obtener líneas entre dos números de línea en un archivo:

import sys

def file_line(name,start=1,end=sys.maxint):
    lc=0
    with open(s) as f:
        for line in f:
            lc+=1
            if lc>=start and lc<=end:
                yield line


s='/usr/share/dict/words'
l1=list(file_line(s,235880))
l2=list(file_line(s,1,10))
print l1
print l2

Salida:

['Zyrian\n', 'Zyryan\n', 'zythem\n', 'Zythia\n', 'zythum\n', 'Zyzomys\n', 'Zyzzogeton\n']
['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']

Simplemente llámelo con un parámetro para obtener de la línea n - > EOF

 0
Author: the wolf,
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
2012-03-06 06:42:27

Si es una tabla.

pd.read_table("path/to/file", sep="\t", index_col=0, skiprows=17)

 0
Author: O.rka,
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
2016-08-27 21:43:09

Si no desea leer todo el archivo en memoria a la vez, puede usar algunos trucos:

Con next(iterator) puedes avanzar a la siguiente línea:

with open("filename.txt") as f:
     next(f)
     next(f)
     next(f)
     for line in f:
         print(f)

Por supuesto, esto es ligeramente feo, por lo que itertools tiene una mejor manera de hacer esto:

from itertools import islice

with open("filename.txt") as f:
    # start at line 17 and never stop (None), until the end
    for line in islice(f, 17, None):
         print(f)
 0
Author: Azsgy,
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
2018-04-14 20:45:32

Puede usar una Comprensión de lista para convertirla en una sola línea:

[fl.readline() for i in xrange(17)]

Más información sobre la comprensión de listas en PEP 202 y en la documentación de Python .

 -1
Author: Niklas R,
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
2012-03-06 05:59:49