Прочитайте файл в обратном порядке, используя python

Как читать файл в обратном порядке с помощью python? Я хочу прочитать файл из последней строки в первую строку.

Ответ 1

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

И в Python 3:

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

Ответ 2

Правильный, эффективный ответ, написанный как генератор.

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 concat the segment to the last line of new chunk.
                # Instead, yield the segment first 
                if buffer[-1] != '\n':
                    lines[-1] += segment
                else:
                    yield segment
            segment = lines[0]
            for index in range(len(lines) - 1, 0, -1):
                if lines[index]:
                    yield lines[index]
        # Don't yield None if the file was empty
        if segment is not None:
            yield segment

Ответ 3

Как насчет чего-то вроде этого:

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

Поскольку файл читается символом по символу в обратном порядке, он будет работать даже на очень больших файлах, если отдельные строки вписываются в память.

Ответ 4

Вы также можете использовать модуль Python file_read_backwards.

После его установки, через pip install file_read_backwards (v1.2.1), вы можете прочитать весь файл в обратном pip install file_read_backwards (по строкам) эффективным способом, используя:

#!/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

Он поддерживает кодировки utf-8, latin-1 и ascii.

Поддержка также доступна для python3. Дополнительную документацию можно найти по адресу http://file-read-backwards.readthedocs.io/en/latest/readme.html.

Ответ 5

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

Если вы используете linux, вы можете использовать команду tac.

$ tac file

2 рецепта вы можете найти в ActiveState здесь и здесь

Ответ 6

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)

Ответ 7

Здесь вы можете найти мою мою реализацию, вы можете ограничить использование ram, изменив переменную "buffer", есть ошибка, что программа печатает пустую строку в начале.

А также использование бара может увеличиваться, если нет новых строк для более чем байтов в буфере, переменная "утечка" будет увеличиваться до появления новой строки ( "\n" ).

Это также работает для файлов размером 16 ГБ, что больше, чем моя общая память.

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

Ответ 8

простая функция для создания второго файла с обратным (только для Linux):

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

как пользоваться

tac('ordered.csv', 'reversed.csv')
f = open('reversed.csv')

Ответ 9

Спасибо за ответ @srohde. У этого есть небольшая ошибка проверки для символа новой строки с оператором 'is', и я не мог прокомментировать ответ с 1 репутацией. Кроме того, я хотел бы управлять открытым файлом, потому что это позволяет мне встроить мои промахи для задач luigi.

Мне нужно было изменить форму:

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

Мне бы хотелось перейти на:

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

Вот измененный ответ, который требует дескриптор файла и сохраняет символы новой строки:

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

Ответ 10

Принятый ответ не будет работать для случаев с большими файлами, которые не помещаются в памяти (что не редкость).

Как отметили другие, ответ @srohde выглядит хорошо, но у него есть следующие проблемы:

  • открытый файл выглядит избыточным, когда мы можем передать объект файла и оставить его пользователю, чтобы решить, в какой кодировке он должен быть прочитан,
  • даже если мы реорганизуем прием файлового объекта, он не будет работать для всех кодировок: мы можем выбрать файл с кодировкой utf-8 и содержимым, отличным от ascii, например

    й
    

    передайте buf_size равный 1 и получите

    UnicodeDecodeError: 'utf8' codec can't decode byte 0xb9 in position 0: invalid start byte
    

    конечно, текст может быть больше, но можно выбрать buf_size так что это приведет к запутанной ошибке, как указано выше,

  • мы не можем указать пользовательский разделитель строк,
  • мы не можем сохранить разделитель строк.

Итак, учитывая все эти проблемы, я написал отдельные функции:

  • тот, который работает с байтовыми потоками,
  • второй, который работает с текстовыми потоками и делегирует свой основной поток байтов первому и декодирует результирующие строки.

Прежде всего, давайте определим следующие служебные функции:

ceil_division для деления с потолком (в отличие от стандартного // деления с полом, дополнительную информацию можно найти в этой теме)

def ceil_division(left_number, right_number):
    """
    Divides given numbers with ceiling.
    """
    return -(-left_number // right_number)

split для разделения строки заданным разделителем с правого конца с возможностью его сохранения:

def split(string, separator, keep_separator):
    """
    Splits given string by given separator.
    """
    parts = string.split(separator)
    if keep_separator:
        *parts, last_part = parts
        parts = [part + separator for part in parts]
        if last_part:
            return parts + [last_part]
    return parts

read_batch_from_end для чтения пакета из правого конца двоичного потока

def read_batch_from_end(byte_stream, size, end_position):
    """
    Reads batch from the end of given byte stream.
    """
    if end_position > size:
        offset = end_position - size
    else:
        offset = 0
        size = end_position
    byte_stream.seek(offset)
    return byte_stream.read(size)

После этого мы можем определить функцию для чтения потока байтов в обратном порядке:

import functools
import itertools
import os
from operator import methodcaller, sub


def reverse_binary_stream(byte_stream, batch_size=None,
                          lines_separator=None,
                          keep_lines_separator=True):
    if lines_separator is None:
        lines_separator = (b'\r', b'\n', b'\r\n')
        lines_splitter = methodcaller(str.splitlines.__name__,
                                      keep_lines_separator)
    else:
        lines_splitter = functools.partial(split,
                                           separator=lines_separator,
                                           keep_separator=keep_lines_separator)
    stream_size = object_.seek(0, os.SEEK_END)
    if batch_size is None:
        batch_size = stream_size or 1
    batches_count = ceil_division(stream_size, batch_size)
    remaining_bytes_indicator = itertools.islice(
            itertools.accumulate(itertools.chain([stream_size],
                                                 itertools.repeat(batch_size)),
                                 sub),
            batches_count)
    try:
        remaining_bytes_count = next(remaining_bytes_indicator)
    except StopIteration:
        return

    def read_batch(position: int) -> bytes:
        result = read_batch_from_end(object_,
                                     size=batch_size,
                                     end_position=position)
        while result.startswith(lines_separator):
            try:
                position = next(remaining_bytes_indicator)
            except StopIteration:
                break
            result = (read_batch_from_end(object_,
                                          size=batch_size,
                                          end_position=position)
                      + result)
        return result

    batch = read_batch(remaining_bytes_count)
    segment, *lines = lines_splitter(batch)
    yield from reverse(lines)
    for remaining_bytes_count in remaining_bytes_indicator:
        batch = read_batch(remaining_bytes_count)
        lines = lines_splitter(batch)
        if batch.endswith(lines_separator):
            yield segment
        else:
            lines[-1] += segment
        segment, *lines = lines
        yield from reverse(lines)
    yield segment

и, наконец, функция для изменения текстового файла может быть определена так:

import codecs


def reverse_file(file, batch_size=None, 
                 lines_separator=None,
                 keep_lines_separator=True):
    encoding = file.encoding
    if lines_separator is not None:
        lines_separator = lines_separator.encode(encoding)
    yield from map(functools.partial(codecs.decode,
                                     encoding=encoding),
                   reverse_binary_stream(
                           file.buffer,
                           batch_size=batch_size,
                           lines_separator=lines_separator,
                           keep_lines_separator=keep_lines_separator))

тесты

Препараты

Я сгенерировал 4 файла с fsutil команды fsutil:

  1. empty.txt без содержимого, размер 0MB
  2. tiny.txt размером 1 МБ
  3. small.txt размером 10 МБ
  4. large.txt размером 50 МБ

Также я реорганизовал решение @srohde для работы с файловым объектом вместо пути к файлу.

Тестовый скрипт

from timeit import Timer

repeats_count = 7
number = 1
create_setup = ('from collections import deque\n'
                'from __main__ import reverse_file, reverse_readline\n'
                'file = open("{}")').format
srohde_solution = ('with file:\n'
                   '    deque(reverse_readline(file,\n'
                   '                           buf_size=8192),'
                   '          maxlen=0)')
azat_ibrakov_solution = ('with file:\n'
                         '    deque(reverse_file(file,\n'
                         '                       lines_separator="\\n",\n'
                         '                       keep_lines_separator=False,\n'
                         '                       batch_size=8192), maxlen=0)')
print('reversing empty file by "srohde"',
      min(Timer(srohde_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing empty file by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('empty.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing tiny file (1MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('tiny.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing small file (10MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('small.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "srohde"',
      min(Timer(srohde_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))
print('reversing large file (50MB) by "Azat Ibrakov"',
      min(Timer(azat_ibrakov_solution,
                create_setup('large.txt')).repeat(repeats_count, number)))

Примечание: я использовал класс collections.deque для генерации выхлопных газов.

Выходы

Для PyPy 3.5 в Windows 10:

reversing empty file by "srohde" 8.31e-05
reversing empty file by "Azat Ibrakov" 0.00016090000000000028
reversing tiny file (1MB) by "srohde" 0.160081
reversing tiny file (1MB) by "Azat Ibrakov" 0.09594989999999998
reversing small file (10MB) by "srohde" 8.8891863
reversing small file (10MB) by "Azat Ibrakov" 5.323388100000001
reversing large file (50MB) by "srohde" 186.5338368
reversing large file (50MB) by "Azat Ibrakov" 99.07450229999998

Для CPython 3.5 в Windows 10:

reversing empty file by "srohde" 3.600000000000001e-05
reversing empty file by "Azat Ibrakov" 4.519999999999958e-05
reversing tiny file (1MB) by "srohde" 0.01965560000000001
reversing tiny file (1MB) by "Azat Ibrakov" 0.019207699999999994
reversing small file (10MB) by "srohde" 3.1341862999999996
reversing small file (10MB) by "Azat Ibrakov" 3.0872588000000007
reversing large file (50MB) by "srohde" 82.01206720000002
reversing large file (50MB) by "Azat Ibrakov" 82.16775059999998

Таким образом, как мы видим, он работает как оригинальное решение, но является более общим и свободным от недостатков, перечисленных выше.


Реклама

Я добавил это в версию lz пакета 0.3.0 (требуется Python 3. 5+), в которой есть много хорошо протестированных функциональных/итерационных утилит.

Можно использовать как

 import io
 from lz.iterating import reverse
 ...
 with open('path/to/file') as file:
     for line in reverse(file, batch_size=io.DEFAULT_BUFFER_SIZE):
         print(line)

Он поддерживает все стандартные кодировки (возможно, кроме utf-7 так как мне сложно определить стратегию для генерации кодируемых строк).

Ответ 12

с открытым ("имя файла") как f:

    print(f.read()[::-1])

Ответ 13

def reverse_lines(filename):
    y=open(filename).readlines()
    return y[::-1]

Ответ 14

Всегда используйте with при работе с файлами, поскольку он обрабатывает все для вас:

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

Или в Python 3:

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

Ответ 15

вам нужно будет сначала открыть файл в формате чтения, сохранить его в переменной, а затем открыть второй файл в формате записи, где вы будете писать или добавлять эту переменную, используя срез [:: -1], полностью меняя файл, Вы также можете использовать readlines(), чтобы превратить его в список строк, с которыми вы можете манипулировать

def copy_and_reverse(filename, newfile):
    with open(filename) as file:
        text = file.read()
    with open(newfile, "w") as file2:
        file2.write(text[::-1])

Ответ 16

Большинство ответов необходимо прочитать весь файл, прежде чем что-либо делать. Этот образец читает все более крупные образцы с конца.

Я только видел, как Мюрат Юкселен отвечал во время написания этого ответа. Это почти то же самое, что я считаю хорошим. В приведенном ниже примере также рассматривается \r и увеличивается его буферизация на каждом шаге. У меня также есть некоторые модульные тесты для поддержки этого кода.

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

Ответ 17

Прочитайте файл по строкам, а затем добавьте его в список в обратном порядке.

Вот пример кода:

reverse = []
with open("file.txt", "r") as file:
    for line in file:
        line = line.strip()
         reverse[0:0] = line

Ответ 18

import sys
f = open(sys.argv[1] , 'r')
for line in f.readlines()[::-1]:
    print line

Ответ 19

Я должен был сделать это некоторое время назад и использовал приведенный ниже код. Он подключается к оболочке. Я боюсь, что у меня больше нет script. Если вы работаете в операционной системе unixish, вы можете использовать "tac", но, например, Команда Mac OSX tac не работает, используйте tail -r. Ниже приведен фрагмент кода, для которого вы находитесь, и соответственно корректирует команду.

# 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)