programing

파일을 역순으로 읽는 방법은?

cafebook 2023. 7. 7. 21:07
반응형

파일을 역순으로 읽는 방법은?

파이썬을 사용하여 파일을 역순으로 읽는 방법은 무엇입니까?저는 마지막 줄부터 첫 줄까지 파일을 읽고 싶습니다.

생성기로 작성된 정확하고 효율적인 답변입니다.

import os

def reverse_readline(filename, buf_size=8192):
    """A generator that returns the lines of a file in reverse order"""
    with open(filename, 'rb') 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)).decode(encoding='utf-8')
            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
for line in reversed(open("filename").readlines()):
    print line.rstrip()

그리고 Python 3에서:

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

파이썬 모듈도 사용할 수 있습니다.file_read_backwards.

설치 후, 다음을 통해pip install file_read_backwards(v1.2.1), 다음을 통해 메모리 효율적인 방식으로 전체 파일을 거꾸로 읽을 수 있습니다.

#!/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" 및 "asci" 인코딩을 지원합니다.

python3에 대해서도 지원이 가능합니다.추가 설명서는 http://file-read-backwards.readthedocs.io/en/latest/readme.html 에서 확인할 수 있습니다.

다음과 같은 것은 어떻습니까?

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

파일은 역순으로 문자별로 읽기 때문에 개별 행이 메모리에 들어가는 한 매우 큰 파일에서도 작동합니다.

허용된 답변은 메모리에 맞지 않는 대용량 파일이 있는 경우에는 작동하지 않습니다(이는 드문 경우가 아닙니다).

다른 사람들이 지적했듯이, @srode 답변은 좋아 보이지만 다음 문제가 있습니다.

  • 파일을 여는 것은 불필요해 보입니다. 파일 객체를 전달하고 사용자에게 어떤 인코딩으로 읽어야 할지 결정하도록 맡길 수 있을 때,
  • 우리가 파일 객체를 수락하도록 요인을 조정하더라도, 그것이 모든 인코딩에 적용되지는 않을 것입니다: 우리는 파일을 선택할 수 있습니다.utf-8인코딩 및 비인코딩 콘텐츠
й

통과하다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 = byte_stream.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):
        result = read_batch_from_end(byte_stream,
                                     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(byte_stream,
                                          size=batch_size,
                                          end_position=position)
                      + result)
        return result

    batch = read_batch(remaining_bytes_count)
    segment, *lines = lines_splitter(batch)
    yield from lines[::-1]
    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 lines[::-1]
    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개의 파일을 생성했습니다.

  1. empty.txt(내용 없음), 크기 0MB
  2. 1MB 크기의 tiny.txt
  3. 10MB 크기의 small.txt
  4. large.txt(50MB 크기)

또한 파일 경로 대신 파일 개체로 작업하기 위해 @srode 솔루션을 리팩터링했습니다.

테스트 스크립트

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클래스에서 배기 발전기까지.

출력

Windows 10에서 PyPy 3.5의 경우:

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

윈도우즈 10에서 CPython 3.5의 경우:

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

따라서 기존 솔루션과 동일한 성능을 제공하지만, 보다 일반적이며 위에 나열된 단점이 없습니다.


광고

는 이것을 했니습다추에 0.3.0테스트를 거친 기능/반복 유틸리티가 많은 패키지 버전(Python 3.5+ 필요).

다음과 같이 사용할 수 있습니다.

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

모든 표준 인코딩을 지원합니다(아마도 다음을 제외함).utf-7코드화 가능한 문자열을 생성하는 전략을 정의하기 어렵기 때문입니다.)

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)
for line in reversed(open("file").readlines()):
    print line.rstrip()

에서는 Linux를 할 수 .tac지휘권

$ tac file

액티브 스테이트에서 찾을 수 있는 2가지 요리법은 여기와 여기에 있습니다.

@srode에 대한 답변 감사합니다.'is' 연산자로 줄바꿈 문자를 확인하는 작은 버그가 있으며, 저는 1평으로 답변에 대해 코멘트할 수 없었습니다.또한 루이지 작업을 위해 내 횡설수설할 수 있기 때문에 외부에서 파일을 열어 관리하고 싶습니다.

변경해야 할 사항은 다음과 같습니다.

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

여기에서 내 구현을 찾을 수 있고, "버퍼" 변수를 변경하여 RAM 사용을 제한할 수 있으며, 프로그램이 처음에 빈 줄을 인쇄하는 버그가 있습니다.

또한 버퍼 바이트 이상에 대한 새 줄이 없을 경우 RAM 사용량이 증가할 수 있으며, "누출" 변수는 새 줄("\n")이 표시될 때까지 증가합니다.

이것은 또한 내 총 메모리보다 큰 16GB 파일에도 작동합니다.

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

반대로 두 번째 파일을 만드는 간단한 기능(리눅스 전용):

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

사용법

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

파일 크기/메모리 사용량이 걱정되는 경우 파일을 메모리에 매핑하고 새 줄을 거꾸로 검색하는 것이 해결책입니다.

텍스트 파일에서 문자열을 검색하는 방법은 무엇입니까?

f와 같이 open filename("""):

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

여기 두 개의 문자열 버퍼를 사용하는 Python 3.8+ 접근 방식이 있습니다. grep와 같은 하위 문자열 일치(또는 빈 하위 문자열이 전달되면 각 줄을 반복하기만 하면 됩니다).모든 파일을 메모리에 로드하는 것보다 메모리 효율성이 더 높을 것으로 예상됩니다. 예를 들어 파일 끝에서 무언가를 찾으려는 경우 버퍼 크기를 제어할 수 있습니다.여기 요지.

from __future__ import annotations

from io import StringIO, SEEK_END
from pathlib import Path
from typing import Iterator, TextIO


def grep_backwards(
    fh: TextIO,
    match_substr: str,
    line_ending: str = "\n",
    strip_eol: bool = False,
    step: int = 10,
) -> Iterator[str]:
    """
    Helper for scanning a file line by line from the end, imitating the behaviour of
    the Unix command line tools ``grep`` (when passed ``match_substr``) or ``tac`` (when
    ``match_substr`` is the empty string ``""``, i.e. matching all lines).

    Args:
      fh            : The file handle to read from
      match_substr  : Substring to match at. If given as the empty string, gives a
                      reverse line iterator rather than a reverse matching line iterator.
      line_ending   : The line ending to split lines on (default: "\n" newline)
      strip_eol     : Whether to strip (default: ``True``) or keep (``False``) line
                      endings off the end of the strings returned by the iterator.
      step          : Number of characters to load into chunk buffer (i.e. chunk size)
    """
    # Store the end of file (EOF) position as we are advancing backwards from there
    file_end_pos = fh.seek(0, SEEK_END)  # cursor has moved to EOF
    # Keep a reversed string line buffer as we are writing right-to-left
    revlinebuf = StringIO()
    # Keep a [left-to-right] string buffer as we read left-to-right, one chunk at a time
    chunk_buf = StringIO()
    # Initialise 'last chunk start' at position after the EOF (unreachable by ``read``)
    last_chunk_start = file_end_pos + 1
    line_offset = 0  # relative to SEEK_END
    has_EOF_newline = False  # may change upon finding first newline
    # In the worst case, seek all the way back to the start (position 0)
    while last_chunk_start > 0:
        # Ensure that read(size=step) will read at least 1 character
        # e.g. when step=4, last_chunk_start=3, reduce step to 3 --> chunk=[0,1,2]
        if step > last_chunk_start:
            step = last_chunk_start
        chunk_start = last_chunk_start - step
        fh.seek(chunk_start)
        # Read in the chunk for the current step (possibly after pre-existing chunks)
        chunk_buf.write(fh.read(step))
        while chunk := chunk_buf.getvalue():
            # Keep reading intra-chunk lines RTL, leaving any leftovers in revlinebuf
            lhs, EOL_match, rhs = chunk.rpartition(line_ending)
            if EOL_match:
                if line_offset == 0:
                    has_EOF_newline = rhs == ""
                # Reverse the right-hand-side of the rightmost line_ending and
                # insert it after anything already in the reversed line buffer
                if rhs:
                    # Only bother writing rhs to line buffer if there's anything in it
                    revlinebuf.write(rhs[::-1])
                # Un-reverse the line buffer --> full line after the line_ending match
                completed_line = revlinebuf.getvalue()[::-1]  # (may be empty string)
                # Clear the reversed line buffer
                revlinebuf.seek(0)
                revlinebuf.truncate()
                # `grep` if line matches (or behaves like `tac` if match_substr == "")
                if line_offset == 0:
                    if not has_EOF_newline and match_substr in completed_line:
                        # The 0'th line from the end (by definition) cannot get an EOL
                        yield completed_line
                elif match_substr in (completed_line + line_ending):
                    if not strip_eol:
                        completed_line += line_ending
                    yield completed_line
                line_offset += 1
            else:
                # If line_ending not found in chunk then add entire [remaining] chunk,
                # in reverse, onto the reversed line buffer, before chunk_buf is cleared
                revlinebuf.write(chunk_buf.getvalue()[::-1])
            # The LHS of the rightmost line_ending (if any) may contain another line
            # ending so truncate the chunk to that and re-iterate (else clear chunk_buf)
            chunk_buf.seek(len(lhs))
            chunk_buf.truncate()
        last_chunk_start = chunk_start
    if completed_line := revlinebuf.getvalue()[::-1]:
        # Iteration has reached the line at start of file, left over in the line buffer
        if line_offset == 0 and not has_EOF_newline and match_substr in completed_line:
            # The 0'th line from the end (by definition) cannot get an EOL
            yield completed_line
        elif match_substr in (
            completed_line + (line_ending if line_offset > 1 or has_EOF_newline else "")
        ):
            if line_offset == 1:
                if has_EOF_newline and not strip_eol:
                    completed_line += line_ending
            elif not strip_eol:
                completed_line += line_ending
            yield completed_line
    else:
        raise StopIteration

작동하는 것을 보여주는 몇 가지 테스트가 있습니다. 최대 100개까지 세어 만든 테스트 입력 파일은 'Hi 0', 'Hi 9', 'Hi 18', ...입니다.

  • 그리고 27번에 두 배의 새로운 선을 줍니다.
  • 그리고 파일 끝에 새 줄을 주지 않습니다.
  • 그리고 파일의 끝에 2개의 새로운 줄을 줍니다.
# Write lines counting to 100 saying 'Hi 0', 'Hi 9', ... give number 27 a double newline
str_out = "".join([f"Hi {i}\n" if i != 27 else f"Hi {i}\n\n" for i in range(0, 100, 9)])
example_file = Path("example.txt")
no_eof_nl_file = Path("no_eof_nl.txt")  # no end of file newline
double_eof_nl_file = Path("double_eof_nl.txt")  # double end of file newline

with open(example_file, "w") as f_out:
    f_out.write(str_out)

with open(no_eof_nl_file, "w") as f_out:
    f_out.write(str_out.rstrip("\n"))

with open(double_eof_nl_file, "w") as f_out:
    f_out.write(str_out + "\n")

file_list = [example_file, no_eof_nl_file, double_eof_nl_file]
labels = [
    "EOF_NL    ",
    "NO_EOF_NL ",
    "DBL_EOF_NL",
]

print("------------------------------------------------------------")
print()
print(f"match_substr = ''")
for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        lines_rev_from_iterator = list(grep_backwards(fh=fh, match_substr=""))

    with open(each_file, "r") as fh:
        lines_rev_from_readline = list(reversed(fh.readlines()))

    print(label, f"{lines_rev_from_iterator == lines_rev_from_readline=}")
print()

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        reverse_iterator = grep_backwards(fh=fh, match_substr="")
        first_match = next(reverse_iterator)
    print(label, f"{first_match=}")
print()

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        all_matches = list(grep_backwards(fh=fh, match_substr=""))
    print(label, f"{all_matches=}")
print()
print()
print("------------------------------------------------------------")
print()
print(f"match_substr = 'Hi 9'")

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        reverse_iterator = grep_backwards(fh=fh, match_substr="Hi 9")
        first_match = next(reverse_iterator)
    print(label, f"{first_match=}")
print()

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        all_matches = list(grep_backwards(fh=fh, match_substr="Hi 9"))
    print(label, f"{all_matches=}")
print()
print("------------------------------------------------------------")
print()
print(f"match_substr = '\\n'")

for len_flag in (True, False):
    for label, each_file in zip(labels, file_list):
        with open(each_file, "r") as fh:
            lines_rev_from_iterator = list(grep_backwards(fh=fh, match_substr="\n"))
        if len_flag:
            print(label, f"{len(lines_rev_from_iterator)=}")
        else:
            print(label, f"{lines_rev_from_iterator=}")
    print()

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        reverse_iterator = grep_backwards(fh=fh, match_substr="\n")
        first_match = next(reverse_iterator)
    print(label, f"{first_match=}")
print()

for label, each_file in zip(labels, file_list):
    with open(each_file, "r") as fh:
        all_matches = list(grep_backwards(fh=fh, match_substr="\n"))
    print(label, f"{all_matches=}")
print()
print("------------------------------------------------------------")

------------------------------------------------------------

match_substr = ''
EOF_NL     lines_rev_from_iterator == lines_rev_from_readline=True
NO_EOF_NL  lines_rev_from_iterator == lines_rev_from_readline=True
DBL_EOF_NL lines_rev_from_iterator == lines_rev_from_readline=True

EOF_NL     first_match='Hi 99\n'
NO_EOF_NL  first_match='Hi 99'
DBL_EOF_NL first_match='\n'

EOF_NL     all_matches=['Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
NO_EOF_NL  all_matches=['Hi 99', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
DBL_EOF_NL all_matches=['\n', 'Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']


------------------------------------------------------------

match_substr = 'Hi 9'
EOF_NL     first_match='Hi 99\n'
NO_EOF_NL  first_match='Hi 99'
DBL_EOF_NL first_match='Hi 99\n'

EOF_NL     all_matches=['Hi 99\n', 'Hi 90\n', 'Hi 9\n']
NO_EOF_NL  all_matches=['Hi 99', 'Hi 90\n', 'Hi 9\n']
DBL_EOF_NL all_matches=['Hi 99\n', 'Hi 90\n', 'Hi 9\n']

------------------------------------------------------------

match_substr = '\n'
EOF_NL     len(lines_rev_from_iterator)=13
NO_EOF_NL  len(lines_rev_from_iterator)=12
DBL_EOF_NL len(lines_rev_from_iterator)=14

EOF_NL     lines_rev_from_iterator=['Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
NO_EOF_NL  lines_rev_from_iterator=['Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
DBL_EOF_NL lines_rev_from_iterator=['\n', 'Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']

EOF_NL     first_match='Hi 99\n'
NO_EOF_NL  first_match='Hi 90\n'
DBL_EOF_NL first_match='\n'

EOF_NL     all_matches=['Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
NO_EOF_NL  all_matches=['Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']
DBL_EOF_NL all_matches=['\n', 'Hi 99\n', 'Hi 90\n', 'Hi 81\n', 'Hi 72\n', 'Hi 63\n', 'Hi 54\n', 'Hi 45\n', 'Hi 36\n', '\n', 'Hi 27\n', 'Hi 18\n', 'Hi 9\n', 'Hi 0\n']

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

항상사를 합니다.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)

먼저 파일을 읽기 형식으로 열고 변수에 저장한 다음 [::-1] 조각을 사용하여 변수를 쓰거나 추가할 쓰기 형식의 두 번째 파일을 열어 파일을 완전히 반대로 만들어야 합니다.또한 읽기 라인()을 사용하여 라인 목록으로 만들 수 있으며, 이를 조작할 수 있습니다.

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

대부분의 답변은 어떤 작업을 수행하기 전에 전체 파일을 읽어야 합니다.이 샘플은 에서 점점 더 큰 샘플을 읽습니다.

저는 이 답을 쓰면서 무라트 위크셀렌의 답을 보았을 뿐입니다.그것은 거의 비슷한데, 저는 그것이 좋은 것이라고 생각합니다.아래 샘플은 또한 \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

파일을 한 줄씩 읽은 다음 역순으로 목록에 추가합니다.

다음은 코드의 예입니다.

reverse = []
with open("file.txt", "r") as file:
    for line in file:
        line = line.strip()
         reverse[0:0] = line
import sys
f = open(sys.argv[1] , 'r')
for line in f.readlines()[::-1]:
    print line
def previous_line(self, opened_file):
        opened_file.seek(0, os.SEEK_END)
        position = opened_file.tell()
        buffer = bytearray()
        while position >= 0:
            opened_file.seek(position)
            position -= 1
            new_byte = opened_file.read(1)
            if new_byte == self.NEW_LINE:
                parsed_string = buffer.decode()
                yield parsed_string
                buffer = bytearray()
            elif new_byte == self.EMPTY_BYTE:
                continue
            else:
                new_byte_array = bytearray(new_byte)
                new_byte_array.extend(buffer)
                buffer = new_byte_array
        yield None

사용할 항목:

opened_file = open(filepath, "rb")
iterator = self.previous_line(opened_file)
line = next(iterator) #one step
close(opened_file)

전에 언급된 이 없는 것 같은데, 사용하는 것은.dequecollections그리고.reverse내게 맞는 것:

from collections import deque

fs = open("test.txt","rU")
fr = deque(fs)
fr.reverse()  # reverse in-place, returns None

for li in fr:
   print li

fs.close()

나는 얼마 전에 이것을 해야 했고 아래 코드를 사용했습니다.그것은 껍데기에 파이프로 연결됩니다.유감스럽게도 저는 더 이상 완전한 대본을 가지고 있지 않습니다.유닉스 운영 체제에서 "tac"을 사용할 수 있지만, 예를 들어 "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)

언급URL : https://stackoverflow.com/questions/2301789/how-to-read-a-file-in-reverse-order

반응형