Printing unix Line endings from Windows.

John Machin sjmachin at lexicon.net
Tue Dec 5 04:00:25 EST 2006


Ant wrote:
> Larry Bates wrote:
>
> > Ant wrote:
> ...
> > > Is there any way of doing this without having to post-process the file
> > > in binary mode (a-la the crlf.py script)
> ...
> > You can write to a new file and create your own line endings.
> > When done, delete the original file and rename the output file.
>
> How can I create my own line endings? I've tried setting os.linesep =
> "\n",  (and to \x0a). I've tried things like:
>
> print "xxx yyy \n",
> print "xxx uuu \x0a",
> filehandle.write("xxx \n")
> filehandle.write("xxx \x0a")
>
> and all of these give me a nice windows-style crlf!
>
> Surely there must be a way to do this ...

and there is: open your output file in binary mode; then it won't
convert every \n to \r\n.

writing:
| >>> f = open('unixlf.txt', 'wb')
| >>> f.write('foo\n')
| >>> f.write('bar\n')
| >>> f.close()

checking:
| >>> f = open('unixlf.txt', 'rb')
| >>> x = f.read()
| >>> x
| 'foo\nbar\n'
| >>> len(x)
| 8

BTW:
| >>> '\n' is '\x0a'
| True

HTH,
John




More information about the Python-list mailing list