Leer un archivo en orden inverso usando python


Cómo leer un archivo en orden inverso usando python? Quiero leer un archivo de la última línea a la primera línea.

Author: Nick Volynkin, 2010-02-20

15 answers

for line in reversed(open("filename").readlines()):
    print line.rstrip()

Y en Python 3:

for line in reversed(list(open("filename"))):
    print(line.rstrip())
 59
Author: Matt Joiner,
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-03-07 03:24:21

Una respuesta correcta y eficiente escrita como generador.

import os

def reverse_readline(filename, buf_size=8192):
    """a generator that returns the lines of a file in reverse order"""
    with open(filename) as fh:
        segment = None
        offset = 0
        fh.seek(0, os.SEEK_END)
        file_size = remaining_size = fh.tell()
        while remaining_size > 0:
            offset = min(file_size, offset + buf_size)
            fh.seek(file_size - offset)
            buffer = fh.read(min(remaining_size, buf_size))
            remaining_size -= buf_size
            lines = buffer.split('\n')
            # the first line of the buffer is probably not a complete line so
            # we'll save it and append it to the last line of the next buffer
            # we read
            if segment is not None:
                # if the previous chunk starts right from the beginning of line
                # do not concact the segment to the last line of new chunk
                # instead, yield the segment first 
                if buffer[-1] is not '\n':
                    lines[-1] += segment
                else:
                    yield segment
            segment = lines[0]
            for index in range(len(lines) - 1, 0, -1):
                if len(lines[index]):
                    yield lines[index]
        # Don't yield None if the file was empty
        if segment is not None:
            yield segment
 100
Author: srohde,
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-05-17 08:35:08

¿Qué tal algo como esto:

import os


def readlines_reverse(filename):
    with open(filename) as qfile:
        qfile.seek(0, os.SEEK_END)
        position = qfile.tell()
        line = ''
        while position >= 0:
            qfile.seek(position)
            next_char = qfile.read(1)
            if next_char == "\n":
                yield line[::-1]
                line = ''
            else:
                line += next_char
            position -= 1
        yield line[::-1]


if __name__ == '__main__':
    for qline in readlines_reverse(raw_input()):
        print qline

Dado que el archivo se lee carácter por carácter en orden inverso, funcionará incluso en archivos muy grandes, siempre y cuando las líneas individuales quepan en la memoria.

 16
Author: Berislav Lopac,
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
2014-11-05 01:09:22

También puede usar el módulo python file_read_backwards.

Después de instalarlo, a través de pip install file_read_backwards (v1.2.1), puede leer todo el archivo al revés (en línea) de una manera eficiente de memoria a través de:

#!/usr/bin/env python2.7

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/path/to/file", encoding="utf-8") as frb:
    for l in frb:
         print l

Soporta codificaciones "utf-8","latin-1" y "ascii".

El soporte también está disponible para python3. Puede encontrar más documentación en http://file-read-backwards.readthedocs.io/en/latest/readme.html

 9
Author: user7321751,
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-03-28 02:06:47
for line in reversed(open("file").readlines()):
    print line.rstrip()

Si estás en Linux, puedes usar el comando tac.

$ tac file

2 recetas que puedes encontrar en ActiveState aquí y aquí

 8
Author: ghostdog74,
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
2010-02-20 11:11:00
import re

def filerev(somefile, buffer=0x20000):
  somefile.seek(0, os.SEEK_END)
  size = somefile.tell()
  lines = ['']
  rem = size % buffer
  pos = max(0, (size // buffer - 1) * buffer)
  while pos >= 0:
    somefile.seek(pos, os.SEEK_SET)
    data = somefile.read(rem + buffer) + lines[0]
    rem = 0
    lines = re.findall('[^\n]*\n?', data)
    ix = len(lines) - 2
    while ix > 0:
      yield lines[ix]
      ix -= 1
    pos -= buffer
  else:
    yield lines[0]

with open(sys.argv[1], 'r') as f:
  for line in filerev(f):
    sys.stdout.write(line)
 8
Author: Ignacio Vazquez-Abrams,
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-05-07 02:20:59

Aquí puede encontrar mi implementación, puede limitar el uso de ram cambiando la variable "buffer", hay un error que el programa imprime una línea vacía al principio.

Y también el uso de ram puede aumentar si no hay nuevas líneas para más de bytes de búfer, la variable "leak" aumentará hasta ver una nueva línea ("\n").

Esto también funciona para archivos de 16 GB, que es más grande que mi memoria total.

import os,sys
buffer = 1024*1024 # 1MB
f = open(sys.argv[1])
f.seek(0, os.SEEK_END)
filesize = f.tell()

division, remainder = divmod(filesize, buffer)
line_leak=''

for chunk_counter in range(1,division + 2):
    if division - chunk_counter < 0:
        f.seek(0, os.SEEK_SET)
        chunk = f.read(remainder)
    elif division - chunk_counter >= 0:
        f.seek(-(buffer*chunk_counter), os.SEEK_END)
        chunk = f.read(buffer)

    chunk_lines_reversed = list(reversed(chunk.split('\n')))
    if line_leak: # add line_leak from previous chunk to beginning
        chunk_lines_reversed[0] += line_leak

    # after reversed, save the leakedline for next chunk iteration
    line_leak = chunk_lines_reversed.pop()

    if chunk_lines_reversed:
        print "\n".join(chunk_lines_reversed)
    # print the last leaked line
    if division - chunk_counter < 0:
        print line_leak
 2
Author: Bekir Dogan,
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-02-27 18:01:17

Gracias por la respuesta @srohde. Tiene un pequeño error comprobando el carácter de nueva línea con el operador' is', y no pude comentar la respuesta con 1 reputación. También me gustaría administrar el archivo abierto afuera porque eso me permite incrustar mis divagaciones para las tareas de luigi.

Lo que necesitaba cambiar tiene la forma:

with open(filename) as fp:
    for line in fp:
        #print line,  # contains new line
        print '>{}<'.format(line)

Me encantaría cambiar a:

with open(filename) as fp:
    for line in reversed_fp_iter(fp, 4):
        #print line,  # contains new line
        print '>{}<'.format(line)

Aquí hay una respuesta modificada que quiere un controlador de archivo y mantiene nuevas líneas:

def reversed_fp_iter(fp, buf_size=8192):
    """a generator that returns the lines of a file in reverse order
    ref: https://stackoverflow.com/a/23646049/8776239
    """
    segment = None  # holds possible incomplete segment at the beginning of the buffer
    offset = 0
    fp.seek(0, os.SEEK_END)
    file_size = remaining_size = fp.tell()
    while remaining_size > 0:
        offset = min(file_size, offset + buf_size)
        fp.seek(file_size - offset)
        buffer = fp.read(min(remaining_size, buf_size))
        remaining_size -= buf_size
        lines = buffer.splitlines(True)
        # the first line of the buffer is probably not a complete line so
        # we'll save it and append it to the last line of the next buffer
        # we read
        if segment is not None:
            # if the previous chunk starts right from the beginning of line
            # do not concat the segment to the last line of new chunk
            # instead, yield the segment first
            if buffer[-1] == '\n':
                #print 'buffer ends with newline'
                yield segment
            else:
                lines[-1] += segment
                #print 'enlarged last line to >{}<, len {}'.format(lines[-1], len(lines))
        segment = lines[0]
        for index in range(len(lines) - 1, 0, -1):
            if len(lines[index]):
                yield lines[index]
    # Don't yield None if the file was empty
    if segment is not None:
        yield segment
 2
Author: Murat Yükselen,
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
2017-10-14 15:18:16

Una función simple para crear un segundo archivo invertido (solo linux):

import os
def tac(file1, file2):
     print(os.system('tac %s > %s' % (file1,file2)))

Cómo usar

tac('ordered.csv', 'reversed.csv')
f = open('reversed.csv')
 2
Author: Alexandre Andrade,
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-02-07 05:24:25

Si le preocupa el tamaño del archivo / el uso de memoria, la asignación de memoria del archivo y el escaneo hacia atrás para buscar nuevas líneas es una solución:

¿Cómo buscar una cadena en archivos de texto?

 1
Author: Federico,
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-02-08 10:29:46
def reverse_lines(filename):
    y=open(filename).readlines()
    return y[::-1]
 0
Author: Gareema,
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-11-13 05:32:01

Siempre use with cuando trabaje con archivos, ya que maneja todo por usted:

with open('filename', 'r') as f:
    for line in reversed(f.readlines()):
        print line

O en Python 3:

with open('filename', 'r') as f:
    for line in reversed(list(f.readlines())):
        print(line)
 0
Author: Carlos Afonso,
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-02 15:19:59

Primero tendría que abrir su archivo en formato de lectura, guardarlo en una variable, luego abrir el segundo archivo en formato de escritura donde escribiría o agregaría la variable usando un segmento [::-1], invirtiendo completamente el archivo. También puedes usar readlines() para convertirlo en una lista de líneas, que puedes manipular

def copy_and_reverse(filename, newfile):
    with open(filename) as file:
        text = file.read()
    with open(newfile, "w") as file2:
        file2.write(text[::-1])
 0
Author: PawlakJ,
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-06-07 12:47:47

La mayoría de las respuestas necesitan leer todo el archivo antes de hacer nada. Esta muestra lee muestras cada vez más grandes desde el final.

Solo vi la respuesta de Murat Yükselen mientras escribía esta respuesta. Es casi lo mismo, lo que supongo que es algo bueno. La siguiente muestra también trata con \r y aumenta su tamaño del búfer en cada paso. También tengo algunas pruebas unitarias para respaldar este código.

def readlines_reversed(f):
    """ Iterate over the lines in a file in reverse. The file must be
    open in 'rb' mode. Yields the lines unencoded (as bytes), including the
    newline character. Produces the same result as readlines, but reversed.
    If this is used to reverse the line in a file twice, the result is
    exactly the same.
    """
    head = b""
    f.seek(0, 2)
    t = f.tell()
    buffersize, maxbuffersize = 64, 4096
    while True:
        if t <= 0:
            break
        # Read next block
        buffersize = min(buffersize * 2, maxbuffersize)
        tprev = t
        t = max(0, t - buffersize)
        f.seek(t)
        lines = f.read(tprev - t).splitlines(True)
        # Align to line breaks
        if not lines[-1].endswith((b"\n", b"\r")):
            lines[-1] += head  # current tail is previous head
        elif head == b"\n" and lines[-1].endswith(b"\r"):
            lines[-1] += head  # Keep \r\n together
        elif head:
            lines.append(head)
        head = lines.pop(0)  # can be '\n' (ok)
        # Iterate over current block in reverse
        for line in reversed(lines):
            yield line
    if head:
        yield head
 0
Author: Almar,
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-09-10 21:35:22

Tuve que hacer esto hace algún tiempo y usé el siguiente código. Va hasta el caparazón. Me temo que ya no tengo el guión completo. Si está en un sistema operativo unixish, puede usar "tac", sin embargo, por ejemplo, el comando Mac OSX tac no funciona, use tail-r. El siguiente fragmento de código prueba para qué plataforma está y ajusta el comando en consecuencia

# We need a command to reverse the line order of the file. On Linux this
# is 'tac', on OSX it is 'tail -r'
# 'tac' is not supported on osx, 'tail -r' is not supported on linux.

if sys.platform == "darwin":
    command += "|tail -r"
elif sys.platform == "linux2":
    command += "|tac"
else:
    raise EnvironmentError('Platform %s not supported' % sys.platform)
 -2
Author: jeorgen,
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
2011-12-07 23:20:03