Retaining Unix EOL when reading/writing in windows

Diez B. Roggisch deets at nospam.web.de
Wed Jan 18 10:19:16 EST 2006


Nick Wain wrote:
> I'm relatively new to PYTHON, using PYTHON 2.4 on Windows XP. I'm having a
> problem as below. I've asked some other people in my office who are more
> experienced in PYTHON, but they can't help.
> 
> I have a number of files created in UNIX that have the UNIX end of line
> (EOL) character.
> 
> I want to read these files in python, modify some lines, and then write
> them to a new file. This appears to work fine, however I find that the
> output files have Windows EOL characters. This is a pain, as I want to
> compare the before and after files to see if my changes are correct.
> 
> I've simplified my code down to something that just reads a file and then
> writes it to a different file. I'm currently doing this with a bit of code
> that looks something like this:
> 
> filename = "test.lwc"
> outfile = open("test_out.lwc", 'w' )
> readfile = open(filename,'r').readlines()
> 
> for line in readfile:
>     outfile.write(line)
> outfile.close()
> 
> Is there a way I can do this, but retain the UNIX EOL characters?

Try using the 'b'-flag as filemode. 

filename = "test.lwc"
outfile = open("test_out.lwc", 'wb' )
readfile = open(filename,'rb').readlines()
 
for line in readfile:
    outfile.write(line)
outfile.close()

Not sure how well that plays with readline, as I have no Windows machine at
hand.

Diez



More information about the Python-list mailing list