fileinput module doesn't work to spec?

Donn Cave donn at u.washington.edu
Tue Oct 24 16:16:31 EDT 2000


Quoth Dale Strickland-Clark <dale at out-think.NOSPAMco.uk>:

| I understand how the redirection works now but what happens if you
| need to write out the last line read? Is the redirection still around?

I don't think so.  It depends on what you mean.  That input() function
actually returns a class instance that supports access as a sequence,
and the "for" loop exercises that support one item at a time.  Each
time, the fileinput object calls file object readline().  As long as
readline() returns a valid input, the loop continues to execute, and
the output continues to be redirected accordingly, and that certainly
includes the last line of the file.

However, you can't easily see into the future and identify the last
line as such, and of course you don't want to wait till after the
loop because the redirection will have been lost.  If you need that,
and really want to use this fileinput system too, I guess you could
subclass FileInput, and augment its readline() and nextfile() methods
to add a last+1 line.  Also have to increment the _lineno attribute.

	Donn Cave, donn at u.washington.edu
----------------------------------------
class FI(fileinput.FileInput):
	SPUD = __name__ + '_spud'
	def readline(self):
		if hasattr(self, 'spud'):
			spud = self.spud
			self._lineno = self._lineno + 1
			del self.spud
			return spud
		return fileinput.FileInput.readline(self)
	def nextfile(self):
		self.spud = self.SPUD
		return fileinput.FileInput.nextfile(self)
...
fi = FI(sys.argv[1:], inplace = 1)
for line in fi:
	if line is FI.SPUD:
		...
	else:
		...



More information about the Python-list mailing list