Read last N lines from file fname.
769367
def tail(self, fname, encoding, window, position=None):
        """"""
        if window <= 0:
            raise ValueError('invalid window %r' % window)

        encodings = ENCODINGS
        if encoding:
            encodings = [encoding] + ENCODINGS

        for enc in encodings:
            try:
                f = self.open(encoding=enc)
                if f:
                    return self.tail_read(f, window, position=position)

                return False
            except IOError, err:
                if err.errno == errno.ENOENT:
                    return []
                raise
            except UnicodeDecodeError:
                pass
134170
def readlines(fname, &block)

      i = 0

      File.open(fname, 'rb') do |file|

        loop do

          i = i + 1

          line = file.gets || break

          block.call(line, i)
        end
      end
    end
1004541
def read(self, n=4096):
        

        while True:
            try:
                if hasattr(self.fd, 'recv'):
                    return self.fd.recv(n)
                return os.read(self.fd.fileno(), n)
            except EnvironmentError as e:
                if e.errno not in Stream.ERRNO_RECOVERABLE:
                    raise e
104936
def _read_next(cls, lines: List[str]) -> 'FilePatch':
        
        # keep munching lines until we hit one starting with '---'
        while True:
            if not lines:
                raise Exception("illegal file patch format: couldn't find line starting with '---'")
            line = lines[0]
            if line.startswith('---'):
                break
            lines.pop(0)

        assert lines[0].startswith('---')
        assert lines[1].startswith('+++')
        old_fn = lines.pop(0)[4:].strip()
        new_fn = lines.pop(0)[4:].strip()

        hunks = []
        while lines:
            if not lines[0].startswith('@@'):
                break
            hunks.append(Hunk._read_next(lines))

        return FilePatch(old_fn, new_fn, hunks)
518954
def Read(self, length):
    """"""
    if not self.IsFile():
      raise IOError("%s is not a file." % self.pathspec.last.path)

    available = min(self.size - self.offset, length)
    if available > 0:
      # This raises a RuntimeError in some situations.
      try:
        data = self.fd.read_random(self.offset, available,
                                   self.pathspec.last.ntfs_type,
                                   self.pathspec.last.ntfs_id)
      except RuntimeError as e:
        raise IOError(e)

      self.offset += len(data)

      return data
    return b""
873127
def read(self, n):
    
    while len(self.buf) < n:
      chunk = self.f.recv(4096)
      if not chunk:
        raise EndOfStreamError()
      self.buf += chunk
    res, self.buf = self.buf[:n], self.buf[n:]
    return res
440836
def readline(self, limit=-1, delim=b'\n'):
        
        self._check_readable()
        chunks = []
        while True:
            chunk = self._buffer.get_chunk(limit, delim)
            if not chunk:
                break
            chunks.append(chunk)
            if chunk.endswith(delim):
                break
            if limit >= 0:
                limit -= len(chunk)
                if limit == 0:
                    break
        if not chunks and not self._buffer.eof and self._buffer.error:
            raise compat.saved_exc(self._buffer.error)
        return b''.join(chunks)
1063975
def read_map(fname):
    
    lst = []
    with open(fname, "r") as f:
        for line in f:
            lst.append(line)
    return lst
856941
def read_file(fname):
    
    print("NO - dont use this function read_file(fname):")
    exit(1)
    lst = []
    with open(fname, 'r') as f:
        #hdr = f.readline()
        for line in f:
            lst.append(line.strip('\n'))
    return lst
370270
def Read(self, length=None):
    """"""

    if self.progress_callback:
      self.progress_callback()

    available_to_read = max(0, (self.size or 0) - self.offset)
    if length is None:
      to_read = available_to_read
    else:
      to_read = min(length, available_to_read)

    with FileHandleManager(self.filename) as fd:
      offset = self.file_offset + self.offset
      pre_padding = offset % self.alignment

      # Due to alignment we read some more data than we need to.
      aligned_offset = offset - pre_padding

      fd.Seek(aligned_offset)

      data = fd.Read(to_read + pre_padding)
      self.offset += len(data) - pre_padding

      return data[pre_padding:]
825748
def _read_nlines(filename, nlines):
    
    if nlines < 0:
        with open(filename, 'r') as fh:
            return fh.readlines()

    lines = []
    with open(filename, 'r') as fh:
        for lineno, line in enumerate(fh):
            if lineno == nlines: break
            lines.append(line)
        return lines
394287
def readline(self, size = None):
        ''''''

        if self.closed: raise ValueError('file closed')
        if self._mode in _allowed_write:
            raise Exception('file opened for write only')
        if self._read_finished: return None

        line = b''
        while not line.endswith(b'\n') and not self._read_finished and (size is None or len(line) <= size):
            line += self.read(1)
        return line
330796
def _read(self, limit = None):
      """"""
      # The code that used to be here was self._fh.read(limit)
      # However, this broke on OSX. os.read, however, works fine, but doesn't
      # take the None argument or have any way to specify "read to the end".
      # This emulates that behaviour.
      while True:
         # Check that we haven't closed this file
         if not self._fh:
            return False
         dataread = os.read(self._fh.fileno(), limit or 65535)
         if len(dataread) > 0:
            self._buf += dataread
            if limit is not None:
               return True
         else:
            return False
1209607
def read_lines_from_file(cls_name, filename):
  """"""
  with tf.io.gfile.GFile(filename, "rb") as f:
    lines = [tf.compat.as_text(line)[:-1] for line in f]
  header_line = "%s%s" % (_HEADER_PREFIX, cls_name)
  if lines[0] != header_line:
    raise ValueError("File {fname} does not seem to have been created from "
                     "{name}.save_to_file.".format(
                         fname=filename, name=cls_name))
  metadata_dict = json.loads(lines[1][len(_METADATA_PREFIX):])
  return lines[2:], metadata_dict
1139
def count_lines_in(filename):
    ""
    f = open(filename)                  
    lines = 0
    buf_size = 1024 * 1024
    read_f = f.read # loop optimization
    
    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)
    
    return lines
302434
def _find_last_line_index(contents):
    """"""
    lineno = 0
    headerblock = re.compile(r"^{0}.*$".format(_ALL_COMMENT))

    if not len(contents):
        raise RuntimeError("""File does not not have any contents""")

    while headerblock.match(contents[lineno]):
        if lineno + 1 == len(contents):
            raise RuntimeError("""No end of headerblock in file""")
        lineno = lineno + 1

    if lineno < 2:
        raise RuntimeError("""Headerblock must have at least two lines""")

    return lineno - 1
775898
def next(self):
    """"""
    try:
      next_line = next(self._f)
    except StopIteration:
      self._FinalCheck()
      raise

    self._line_number += 1
    m_eol = re.search(r"[\x0a\x0d]*$", next_line)
    if m_eol.group() == "\x0d\x0a":
      self._crlf += 1
      if self._crlf <= 5:
        self._crlf_examples.append(self._line_number)
    elif m_eol.group() == "\x0a":
      self._lf += 1
      if self._lf <= 5:
        self._lf_examples.append(self._line_number)
    elif m_eol.group() == "":
      # Should only happen at the end of the file
      try:
        next(self._f)
        raise RuntimeError("Unexpected row without new line sequence")
      except StopIteration:
        # Will be raised again when EndOfLineChecker.next() is next called
        pass
    else:
      self._problems.InvalidLineEnd(
        codecs.getencoder('string_escape')(m_eol.group())[0],
        (self._name, self._line_number))
    next_line_contents = next_line[0:m_eol.start()]
    for seq, name in INVALID_LINE_SEPARATOR_UTF8.items():
      if next_line_contents.find(seq) != -1:
        self._problems.OtherProblem(
          "Line contains %s" % name,
          context=(self._name, self._line_number))
    return next_line_contents