[Pythonmac-SIG] Line endings and readline()

Amos Newcombe anewcombe@earthlink.net
Thu, 7 Sep 2000 08:01:37 -0400


>I am trying to run a macpython script on a linux box, but when I try and
>readline() from a saved text file, it gets confused about line endings ( the
>text files are generated on a mac ).
>
>Is there some easy way of convincing python to change what it expects as the
>end-of-line character, to deal with this sort of crodd-platform problem?
>
>Andrew Watson

I do it this way:

	def	readline(self):
		s = self.chBuffer
		self.chBuffer = ''
		while 1:
			c = self.f.read(1)
			if not c: break
			if c == '\n' or c == '\r':
				if c == '\r':
					c = self.f.read(1)
					if c and c != '\n': self.chBuffer = c
				s = s + '\n'
				break
			s = s + c
		if s != '': self.cLines = self.cLines + 1
		return s

This is a method of an object (self) that serves as a general-purpose 
line reader. It has a field f, which contains the result of an open() 
call (or maybe a  urllib.urlopen() call).

This recognizes either '\r', '\n', or '\r\n' as a single line break. 
<insanity> Go crazy with them. Mix and match in the same file! I can 
deal with it all! Muhahahahahahahaha! </insanity note="must be time 
for a break">

Amos Newcombe

PS If there is any interest in this object I will be happy to oblige.
-- 
The difference between theory and practice is that, in theory, there 
is no difference between theory and practice.