gaumann gaumann - 1 month ago 19
Python Question

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

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.

Answer

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'))