end of lines

Joe Francia usenet at soraia.com
Tue Jan 28 14:20:28 EST 2003


This code works for me on Windows XP and ActiveState Python 2.2.2.  I'm 
pretty sure it works on 2.2.1 as well:

code = open(file, 'r').read()
compiled_code = compile(code, '<string>', 'exec')

You could even do this (to be more obscure):

compiled_code = compile(open(file, 'r').read(), '<string>', 'exec')

Some points to note:

* By specifying 'r' when opening the file, Python automagically converts 
line endings for you.
* Using read() does what join() and readlines() do, only in much less code.
* I don't know why you are using urllib.urlopen() to read a local file. 
  open(filename) works just as well.
* Strings cannot be modified in place (they are immutable). 
string.replace(code, "\r", "\n") probably returns the string you want, 
but you never actually store it anywhere.
* If you find you need to use urllib.urlopen() for some reason, you 
probably want to do this, to be safe: code = code.replace('\r\n', '\n')

Joe Francia
www.soraia.com

Eric Mattes wrote:
> Hi.
> 
> I am running Windows XP and activestate python 2.2.1. I'm writing a
> program that reads in a (local) file using urllib and the readlines()
> method like so:
> 
> code = "".join(urllib.urlopen(file).readlines())
> string.replace(code, "\r", "\n")
> compiled_code = compile(code, '<string>', 'exec')
> 
> This causes a SyntaxError "Invalid Syntax" with an arrow pointing at
> the end of the first line of the string read from the file. For
> example, the file's first line is:
> 
> print "hi"
> 
> The error will point to the space just after the "hi"
> 
> I read that the exec and compile functions need lines to end with only
> a newline character, so I put that replace call in there to filter out
> the CRs. It still
> doesn't work! I am really stumped by this one. Any help would be
> appreciated.
> 
> Thanks!
> -Eric





More information about the Python-list mailing list