Seeing next character in an file

Keith Jones kjones9 at
Sun Jul 27 04:58:13 CEST 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 =,1)     # set the file's current position back a character

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

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

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

More information about the Python-list mailing list