Using python to write text files with DOS line endings on linux Using python to write text files with DOS line endings on linux windows windows

Using python to write text files with DOS line endings on linux


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.

For example:

import iowith io.open('tmpfile', 'w', newline='\r\n') as f:    f.write(u'foo\nbar\nbaz\n')

will create a file that contains this:

foo\r\nbar\r\nbaz\r\n


you can look at this PEP for some reference.

Update:

@OP, you can try creating something like this

import sysplat={"win32":"\r\n", 'linux':"\n" } # add macos as wellplatform=sys.platform...o.write( line + plat[platform] )


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

For example:

class ForcedCrLfFile(file):    def write(self, s):        super(ForcedCrLfFile, self).write(s.replace(r'\n', '\r\n'))