Seeing next character in an file

Keith Jones kjones9 at rochester.rr.com
Sat Jul 26 22:58:13 EDT 2003


On Sun, 27 Jul 2003 01:09:54 +0000, Grumfish wrote:

> Is there a way to see the next character of an input file object without 
> advancing the position in the file?


To do this, you can do the following:

fin = file('myfile')

... 

char = fin.read(1)
fin.seek(-1,1)     # set the file's current position back a character

You can then write your own subclass of file, if you want, with "peek"
functionality:

class flexfile(file):
	def __init__(self, fname, mode='r', bufsize=0):
		file.__init__(self, fname, mode, bufsize)

	def peek(self, cnt):
		data = self.read(cnt)
                self.seek(cnt * -1, 1)
		return data
	
	def peekline(self):
		pos = self.tell()
		data = self.readline()
		self.seek(pos, 0)
		return data













More information about the Python-list mailing list