views:

428

answers:

4

I want to write text files with DOS/Windows line endings '\r\n' using python running on Linux. It seems to me that there must be a better way than manually putting a '\r\n' at the end of every line or using a line ending conversion utility. Ideally I would like to be able to do something like assign to os.linesep the separator that I want to use when writing the file. Or specify the line separator when I open the file.

A: 

you can look at this PEP for some reference.

Update:

@OP, you can try creating something like this

import sys
plat={"win32":"\r\n", 'linux':"\n" } # add macos as well
platform=sys.platform
...
o.write( line + plat[platform] )
ghostdog74
"There is no special support for output to file with a different newline convention, and so mode "wU" is also illegal."
Ignacio Vazquez-Abrams
That PEP is about reading files all it says about output is, "There is no special support for output to file with a different newline convention"
gaumann
i thought you just need to write just one format, eg "\n" on linux and then use the "U" mode on windows and it will recognise? if not, my bad for misinterpreting the PEP.
ghostdog74
No, you're right about that, but sometimes a real CRLF is needed.
Ignacio Vazquez-Abrams
I think the PEP nicely deals with the situation where you produce the files on one platform to use on that platform. But I need to produce them on linux i.e. a server for distribution to users of various operating systems including windows.
gaumann
i see. well, if that's the case, using manually `\r\n` is inevitable.
ghostdog74
+1  A: 

Just write a file-like that wraps another file-like and which converts \n to \r\n on write.

Ignacio Vazquez-Abrams
seems to be the best answer for python 2.5 and earlier
gaumann
+1  A: 

I found a good answer for python 2.6 and later. The open function in the io module has an optional newline parameter that lets you specify which newlines you want to use.

gaumann
A: 

You could write a function that converts text then writes it. For example:

def DOSwrite(f, text):
    t2 = text.replace('\n', '\r\n')
    f.write(t2)
#example
f = open('/path/to/file')
DOSwrite(f, "line 1\nline 2")
f.close()
None