Lichen

lib/__builtins__/file.py

580:e703b981b9b1
2017-02-13 Paul Boddie Eliminated redundant struct usage. method-wrapper-for-context
     1 #!/usr/bin/env python     2      3 """     4 File objects.     5      6 Copyright (C) 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk>     7      8 This program is free software; you can redistribute it and/or modify it under     9 the terms of the GNU General Public License as published by the Free Software    10 Foundation; either version 3 of the License, or (at your option) any later    11 version.    12     13 This program is distributed in the hope that it will be useful, but WITHOUT    14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS    15 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more    16 details.    17     18 You should have received a copy of the GNU General Public License along with    19 this program.  If not, see <http://www.gnu.org/licenses/>.    20 """    21     22 from __builtins__.stream import filestream    23 from native import fopen, fread    24     25 class file(filestream):    26     27     "A file abstraction."    28     29     def __init__(self, filename, mode="r", encoding=None, bufsize=1024):    30     31         """    32         Open the file with the given 'filename' using the given access 'mode',    33         any specified 'encoding', and the given 'bufsize'.    34         """    35     36         get_using(filestream.__init__, self)(encoding, bufsize)    37         self.__data__ = fopen(filename, mode)    38         self.buffered = ""    39     40     def _get_data(self):    41     42         "Get data from the file."    43     44         if self.buffered:    45             s = self.buffered    46             self.buffered = ""    47         else:    48             s = fread(self.__data__, self.bufsize)    49     50         return s    51     52     def _read_data(self, l):    53     54         "Read data into 'l'."    55     56         s = self._get_data()    57         l.append(s)    58     59     def _read_until_newline(self, l):    60     61         "Read data into 'l', returning whether a newline has been read."    62     63         s = self._get_data()    64     65         # NOTE: Only POSIX newlines are supported currently.    66     67         i = s.find("\n")    68     69         if i != -1:    70             l.append(s[:i+1])    71             self.buffered = s[i+1:]    72             return True    73     74         l.append(s)    75         return False    76     77 # vim: tabstop=4 expandtab shiftwidth=4