복붙노트

[PYTHON] 파이썬 머리, 꼬리 및 텍스트 파일의 줄을 뒤로 읽어

PYTHON

파이썬 머리, 꼬리 및 텍스트 파일의 줄을 뒤로 읽어

파이썬에서 'head'와 'tail'명령을 구현하고 텍스트 파일의 라인으로 역방향으로 읽는 방법은 무엇입니까?

해결법

  1. ==============================

    1.이것은 내 개인 파일 클래스입니다 ;-)

    이것은 내 개인 파일 클래스입니다 ;-)

    class File(file):
        """ An helper class for file reading  """
    
        def __init__(self, *args, **kwargs):
            super(File, self).__init__(*args, **kwargs)
            self.BLOCKSIZE = 4096
    
        def head(self, lines_2find=1):
            self.seek(0)                            #Rewind file
            return [super(File, self).next() for x in xrange(lines_2find)]
    
        def tail(self, lines_2find=1):  
            self.seek(0, 2)                         #Go to end of file
            bytes_in_file = self.tell()
            lines_found, total_bytes_scanned = 0, 0
            while (lines_2find + 1 > lines_found and
                   bytes_in_file > total_bytes_scanned): 
                byte_block = min(
                    self.BLOCKSIZE,
                    bytes_in_file - total_bytes_scanned)
                self.seek( -(byte_block + total_bytes_scanned), 2)
                total_bytes_scanned += byte_block
                lines_found += self.read(self.BLOCKSIZE).count('\n')
            self.seek(-total_bytes_scanned, 2)
            line_list = list(self.readlines())
            return line_list[-lines_2find:]
    
        def backward(self):
            self.seek(0, 2)                         #Go to end of file
            blocksize = self.BLOCKSIZE
            last_row = ''
            while self.tell() != 0:
                try:
                    self.seek(-blocksize, 1)
                except IOError:
                    blocksize = self.tell()
                    self.seek(-blocksize, 1)
                block = self.read(blocksize)
                self.seek(-blocksize, 1)
                rows = block.split('\n')
                rows[-1] = rows[-1] + last_row
                while rows:
                    last_row = rows.pop(-1)
                    if rows and last_row:
                        yield last_row
            yield last_row
    

    사용 예 :

    with File('file.name') as f:
        print f.head(5)
        print f.tail(5)
        for row in f.backward():
            print row
    
  2. ==============================

    2.머리는 쉽다 :

    머리는 쉽다 :

    from itertools import islice
    with open("file") as f:
        for line in islice(f, n):
            print line
    

    전체 파일을 메모리에 보관하지 않으려면 꼬리가 더 힘듭니다. 입력이 파일 인 경우 파일의 끝에서 시작하여 블록 읽기를 시작할 수 있습니다. 원래 꼬리는 입력이 파이프 인 경우에도 작동하므로보다 일반적인 해결책은 마지막 몇 줄을 제외하고 전체 입력을 읽고 무시하는 것입니다. 이렇게하는 쉬운 방법은 collections.deque입니다.

    from collections import deque
    with open("file") as f:
        for line in deque(f, maxlen=n):
            print line
    

    이 두 코드 스 니펫에서 n은 인쇄 할 줄 수입니다.

  3. ==============================

    3.꼬리:

    꼬리:

    def tail(fname, lines):
        """Read last N lines from file fname."""
        f = open(fname, 'r')
        BUFSIZ = 1024
        f.seek(0, os.SEEK_END)
        fsize = f.tell()
        block = -1
        data = ""
        exit = False
        while not exit:
            step = (block * BUFSIZ)
            if abs(step) >= fsize:
                f.seek(0)
                exit = True
            else:
                f.seek(step, os.SEEK_END)
            data = f.read().strip()
            if data.count('\n') >= lines:
                break
            else:
                block -= 1
        return data.splitlines()[-lines:]
    
  4. from https://stackoverflow.com/questions/5896079/python-head-tail-and-backward-read-by-lines-of-a-text-file by cc-by-sa and MIT license