File-like objects that read from or write to a bsddb record.
This implements (nearly) all stdio methods.
f = DBRecIO(db, key, txn=None)
f.close() # explicitly release resources held
flag = f.isatty() # always false
pos = f.tell() # get current position
f.seek(pos) # set current position
f.seek(pos, mode) # mode 0: absolute; 1: relative; 2: relative to EOF
buf = f.read() # read until EOF
buf = f.read(n) # read up to n bytes
f.truncate([size]) # truncate file at to at most size (default: current pos)
f.write(buf) # write at current position
f.writelines(list) # for line in list: f.write(line)
- fileno() is left unimplemented so that code which uses it triggers
- There's a simple test set (see end of this file) - not yet updated
- readline() is not implemented yet.
Itamar Shtull-Trauring <itamar@maxnm.com>
def __init__(self, db, key, txn=None):
raise ValueError, "I/O operation on closed file"
def seek(self, pos, mode = 0):
raise ValueError, "I/O operation on closed file"
raise ValueError, "I/O operation on closed file"
raise ValueError, "I/O operation on closed file"
newpos = min(self.pos+n, self.len)
r = self.db.get(self.key, txn=self.txn, dlen=dlen, doff=self.pos)
def readline(self, length=None):
raise ValueError, "I/O operation on closed file"
self.buf = self.buf + string.joinfields(self.buflist, '')
i = string.find(self.buf, '\n', self.pos)
if self.pos + length < newpos:
newpos = self.pos + length
r = self.buf[self.pos:newpos]
def readlines(self, sizehint = 0):
if 0 < sizehint <= total:
def truncate(self, size=None):
raise ValueError, "I/O operation on closed file"
raise IOError(errno.EINVAL,
"Negative size not allowed")
self.db.put(self.key, "", txn=self.txn, dlen=self.len-size, doff=size)
raise ValueError, "I/O operation on closed file"
self.buflist.append('\0'*(self.pos - self.len))
newpos = self.pos + len(s)
self.db.put(self.key, s, txn=self.txn, dlen=len(s), doff=self.pos)
def writelines(self, list):
self.write(string.joinfields(list, ''))
raise ValueError, "I/O operation on closed file"
lines = open(file, 'r').readlines()
text = open(file, 'r').read()
raise RuntimeError, 'write failed'
print 'File length =', length
print 'First line =', repr(f.readline())
print 'Second line =', repr(line)
line2 = f.read(len(line))
raise RuntimeError, 'bad result after seek back'
f.seek(f.tell() - len(line))
raise RuntimeError, 'bad result after seek back from EOF'
print 'Read', len(list), 'more lines'
print 'File length =', f.tell()
raise RuntimeError, 'bad length'
if __name__ == '__main__':