ActiveState Code

Recipe 66434: Change line endings


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.

Python
 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

Discussion

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.

Comments

  1. 1. At 12:04 p.m. on 26 jul 2001, Ryan Williams said:

    For converting to DOS, how about:

    import re
    temp = re.sub("\r(?!\n)|(?&lt;!\r)\n", "\r\n", temp)
    
  2. 2. At 1:50 p.m. on 4 sep 2001, Dave Brueck said:

    The standard Python distribution comes with two command-line scripts (in Tools/scripts) called crlf.py and lfcr.py that do this very thing.

  3. 3. At 2:28 p.m. on 18 nov 2001, Gordon Worley (the author) said:

    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.

  4. 4. At 2:29 p.m. on 18 nov 2001, Gordon Worley (the author) said:

    Change made. Thanks.

  5. 5. At 7:13 p.m. on 28 aug 2004, Guy Stone said:

    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

Sign in to comment