readline() with arbitrary end of lines

Manuel Gutierrez Algaba thor at localhost.localdomain
Sun Sep 10 22:20:06 CEST 2000


On Sun, Javier Bezos <see.below at no.spam.es> wrote:
>Hello,
>
>I'm using MacPython 1.5.2c1 to read several files with
>the help of readline(). However, the files to be read can
>have either Mac or Unix end of lines and it seems that only
>Mac end of lines are recognized; changing linesep has no
>effect at all.
>
>Here is an example. With a little file named test.txt
>
>  Line 1
>  Line 2
>  Line 3
>
>and the following short script
>
>  a = open("test.txt", "r")
>  print a.readlines()
>
>I get
>
>  ['Line 1\012', 'Line 2\012', 'Line 3']
>
>with Mac end of lines (right), but
>
>  ['Line 1\015Line 2\015Line 3']

You can do this:

import string
b=[]
for i in a:
	for j in string.split(a,"\015"):
		if j[-1]=="\012":
			b.append(j[-1])
		else:
			b.append(j)


In b there's all the lines, independtly of the OS. 

You can wrap it into a function.

Forgive us for not giving a better solution, we have been
adding more important things like "print>>" and other stuff.

>Can Python detect and convert transparently different
>end of lines (as Tcl or Java can)? If not, can Python read
>until a certain text is found (as AppleScript can)?
>


--- 
MGA



More information about the Python-list mailing list