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
2010-04-15 00:59:49
"There is no special support for output to file with a different newline convention, and so mode "wU" is also illegal."
Ignacio Vazquez-Abrams
2010-04-15 01:01:20
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
2010-04-15 01:04:40
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
2010-04-15 01:05:30
No, you're right about that, but sometimes a real CRLF is needed.
Ignacio Vazquez-Abrams
2010-04-15 01:06:33
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
2010-04-15 01:08:20
i see. well, if that's the case, using manually `\r\n` is inevitable.
ghostdog74
2010-04-15 01:08:52
+1
A:
Just write a file-like that wraps another file-like and which converts \n
to \r\n
on write.
Ignacio Vazquez-Abrams
2010-04-15 01:00:31
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
2010-04-15 02:05:10