Need to unread or push back bytes to a file

Noah Spurrier (a) noahnoah.org
Sat Feb 24 15:03:34 EST 2001


Yeah, this looks good. I was hoping there was a way to do it
using some included library.

Also, this shows why file should be a first class object!
This class would be so much easier if we could just inherit from file.
I want to make sure that my new object can be used anywhere a
file is normally expected. As it currently stands, I will have to
provide wrapper implementations for every method that file supports;
about 12 methods in all.

I don't know how to wrap the file objects read-only attributes.
Does seek() and tell() make sense in this type of file?
At the end I added an expanded version of the class wrapper.

Yours,
Noah

class NSWrapper:
	# I don't know how to wrap these read-only attributes:
	# closed 
	# mode 
	# name 
	# softspace 

	def __init__(self, fileob):
		self.fileob = fileob
		self.buffer = ''
	def close (self):
		self.fileob.close()
		self.buffer = ''
	def flush (self):
		self.fileob.flush()
	def isatty (self):
		return self.fileob.isatty()
	def fileno (self):
		return self.fileob.fileno()
	def push_back(self, piece):
		self.buffer = piece + self.buffer
	def readall(self):
		result = self.buffer + self.fileob.read()
		self.buffer = ''
		return result
	def read (self, size=-1):
		if size <= -1: 
			return self.readall()
		avail = len(self.buffer)
		if size > avail:
			result = self.buffer+file.read(size-avail)
			self.buffer = ''
		else:
			result = self.buffer[:size]
			self.buffer = self.buffer[size:]
		return result
	def readline (self, size=-1):
		return self.fileob.readline(size)
	def readlines (self, sizehint=-1):
		return self.fileob.readlines (sizehint)
	#!!! Some methods don't make sense on a stream.
	#def seek (self, offset, whence=0):
	#	self.fileob.seek (offset, whence)
	#def tell (self):
	#	return self.fileob.tell()
	#def truncate (self, size=-1):
	#	self.fileob.truncate(size)
	def write (self, str):
		self.fileob.write(str)
	def writelines (self, list):
		self.fileob.writelines(list)



> "Noah Spurrier" <noah(a)noah.org> wrote in message
> news:9771ks0ic2 at news2.newsguy.com...
> >
> >
> > I need to push bytes back into a file object.
> > Is there a buffered file wrapper for file objects?
> >  ...
> what about something like:
> 
> class NSWrapper:
>     def __init__(self, fileob):
>  ...
> needs testing, but this should be roughly what you want...?

> Alex



==================================
Posted via http://nodevice.com
Linux Programmer's Site



More information about the Python-list mailing list