SoFunction
Updated on 2024-10-30

Tutorial for a script that implements line break conversion in Python

It's a simple thing to convert between line breaks in '\n', '\r\n', and '\r' 3.
usage

Copy Code The code is as follows.
usage: eol_convert.py [-h] [-r] [-m {u,p,w,m,d}] [-k] [-f]
                      filename [filename ...]

Convert Line Ending

positional arguments:
  filename        file names

optional arguments:
  -h, --help      show this help message and exit
  -r              walk through directory
  -m {u,p,w,m,d}  mode of the line ending
  -k              keep output file date
  -f              force conversion of binary files

source code (computing)

This can only be considered a simple exercise for the argparse module and the os module's utime(), stat(), and walk(). It works, but it's fairly imperfect.

 #!/usr/bin/env python 
  #2009-2011 dbzhang800 
  import os 
  import re 
  import  
   
  def convert_line_endings(temp, mode): 
    if mode in ['u', 'p']: #unix, posix 
      temp = ('\r\n', '\n') 
      temp = ('\r', '\n') 
    elif mode == 'm':   #mac (before Mac OS 9) 
      temp = ('\r\n', '\r') 
      temp = ('\n', '\r') 
    elif mode == 'w':   #windows 
      temp = ("\r(?!\n)|(?<!\r)\n", "\r\n", temp) 
    return temp 
   
  def convert_file(filename, args): 
    statinfo = None 
    with file(filename, 'rb+') as f: 
      data = () 
      if '\0' in data and not : #skip binary file... ? 
        print '%s is a binary file?, skip...' % filename 
        return 
      newdata = convert_line_endings(data, ) 
      if (data != newdata): 
        statinfo = (filename) if  else None 
        (0) 
        (newdata) 
        () 
    if statinfo: 
      (filename, (statinfo.st_atime, statinfo.st_mtime)) 
    print filename 
   
  def walk_dir(d, args): 
    for root, dirs, files in (d): 
      for name in files: 
        convert_file((root, name), args) 
   
  if __name__ == '__main__': 
    import argparse 
    import sys 
    parser = (description='Convert Line Ending') 
    parser.add_argument('filename', nargs='+', help='file names') 
    parser.add_argument('-r', dest='recursive', action='store_true', 
        help='walk through directory') 
    parser.add_argument('-m', dest='mode', default='d', choices='upwmd', 
        help='mode of the line ending') 
    parser.add_argument('-k', dest='keepdate', action='store_true', 
        help='keep output file date') 
    parser.add_argument('-f', dest='force', action='store_true', 
        help='force conversion of binary files') 
    args = parser.parse_args() 
    if  == 'd': 
       = 'w' if  == 'win32' else 'p' 
   
    for filename in : 
      if (filename): 
        if : 
          walk_dir(filename, args) 
        else: 
          print '%s is a directory, skip...' % filename 
      elif (filename): 
        convert_file(filename, args) 
      else: 
        print '%s does not exist' % filename