When working between platforms, it is often necessary to convert the line endings on files for them to work, especially when it comes to code. Pass Unix Python code with \r and it goes nowhere. Same on Mac Python with \n. This code simply and easily fixes the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import string
def convert_line_endings(temp, mode):
#modes: 0 - Unix, 1 - Mac, 2 - DOS
if mode == 0:
temp = string.replace(temp, '\r\n', '\n')
temp = string.replace(temp, '\r', '\n')
elif mode == 1:
temp = string.replace(temp, '\r\n', '\r')
temp = string.replace(temp, '\n', '\r')
elif mode == 2:
import re
temp = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", temp)
return temp
|
This code comes from a command line tool that I wrote that I use all the time when working on OS X with a mixture of Mac and Unix files.
The algorithm was developed because it just jumped out at me as the most elegant way to do this.
For converting to DOS, how about:
The standard Python distribution comes with two command-line scripts (in Tools/scripts) called crlf.py and lfcr.py that do this very thing.
DOS. Ah, so DOS line endings are \r\n, not \n\r. I don't have any DOS formatted files lying around, so I guess I got them mixed up.
Change made. Thanks.
Fine if the entire text fits in memory, but. what if it doesn't? I tried all sorts of line-at-a-time reads in binary mode, but could never find \n or \r\n ending the string. PS I'm running 2.3 on Windows platform