Welcome, guest | Sign In | My Account | Store | Cart

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, 14 lines
 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.

5 comments

Ryan Williams 22 years, 8 months ago  # | flag

For converting to DOS, how about:

import re
temp = re.sub("\r(?!\n)|(?&lt;!\r)\n", "\r\n", temp)
Dave Brueck 22 years, 7 months ago  # | flag

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

Gordon Worley (author) 22 years, 4 months ago  # | flag

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.

Gordon Worley (author) 22 years, 4 months ago  # | flag

Change made. Thanks.

Guy Stone 19 years, 7 months ago  # | flag

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

Created by Gordon Worley on Thu, 26 Jul 2001 (PSF)
Python recipes (4591)
Gordon Worley's recipes (3)

Required Modules

Other Information and Tasks