# textfile.py
#
# Copyright 2002 Wichert Akkerman <wichert@deephackmode.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

"""Simple file abstraction.

The TextFile class which this class implements is a small subset
of the standard python file object which only supports reading
complete lines of text. It keeps track of the filename and linenumber
currently being read, which can be useful to produce more informative
error messages.
"""

__docformat__   = "epytext en"

class TextFile:
	"""Text file

	This class works mostly similar to a standard file object,
	featuring the methods as open(), close() and readline().

	@ivar filename: name of file being read
	@type filename: string
	@ivar lineno:   linenumber last read
	@type lineno:   integer
	@ivar file:     file being read
	@type file:     file object
	"""
	def __init__(self, file=None):
		"""Constructor.

		@param file: name of file to read
		@type file:  string
		"""
		self.filename=None
		self.lineno=0
		self.file=None
		if file:
			self.open(file)


	def open(self, file):
		"""Open a file for reading.

		@param file: name of file to read
		@type file:  string
		"""
		self.filename=file
		self.lineno=0
		self.file=open(file, "rt")


	def close(self):
		"""Close the file and reset context.
		"""
		self.filename=None
		self.lineno=0
		if self.file:
			self.file.close()
			self.file=None


	def readline(self):
		"""Read a line.

		@return: line of text
		@rtype:  string
		"""
		line=self.file.readline()
		self.lineno+=1
		return line

