[Tutor] OS dependence of line separators

Garry Willgoose Garry.Willgoose at newcastle.edu.au
Tue Feb 1 03:38:10 CET 2011


I have a code that needs to run on all platforms and generate text  
output files that can be read on other platforms. I'm a bit confused  
about how Python handles the age-old end of line character/s problem.  
I'm familiar with '\n' and '\r\n' dependence of Unix and Windows  
respectively. Also I'm familiar that the Python manual recommends that  
you use '\n' as the line terminator when writing a file for a  file  
that is to read on that same platform and not to use '\r\n' explicitly  
on Windows. Also os.linesep gives the line terminator for your current  
OS even thought the manual says not to use the value when writing  
files. So the question is what does python do on windows when writing  
a text file ... does it recognise that '\n' needs to be converted to  
'\r\n' and substitute it as its writing. Does this mean that if I have  
an option in my code that sets EOL to '\r\n' (I intend to ask the user  
what platform he's needs to generate the file for) when I need to  
write to a windows file that when on a UNIX machine '\r\n' will be  
output in the file but when I'm on a Windows machine '\r\r\n' will be  
output? If so then I need to find what os.linesep and check what its  
value is before I set what value I give to EOL.

Or is this the case where I need to set 'b' option when opening the  
new file ... which, ughh, requires me to explicitly convert all  
numbers to strings before I write them.


====================================================================
Prof Garry Willgoose,
email:  garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com
email-for-life: garry.willgoose at alum.mit.edu
personal webpage: www.telluricresearch.com/garry
====================================================================
"Do not go where the path may lead, go instead where there is no path  
and leave a trail"
                           Ralph Waldo Emerson
====================================================================





More information about the Tutor mailing list