It's a simple thing to convert between newline characters in ' \ n ', ' \ r \ n ', ' \ R ' 3.
usage
Copy Code code 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 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
This is only a simple exercise for the Utime (), stat (), walk () of the Argparse module and the OS module. Can be used, but still quite imperfect.
#!/usr/bin/env python #2009 -2011 dbzhang800 import OS import re import Os.path def Convert_line_endin GS (temp, mode): If mode in [' U ', ' P ']: #unix, POSIX temp = temp.replace (' \ r \ n ', ' \ n ') temp = Temp.repla CE (' \ r ', ' \ n ') elif mode = = ' m ': #mac (before Mac OS 9) temp = Temp.replace (' \ r \ n ', ' \ r ') Temp = Temp . replace (' \ n ', ' \ R ') elif mode = = ' W ': #windows temp = re.sub ("\ r! \ n) | (? <!\r) \ n "," \ r \ n ", temp) return to temp def convert_file (filename, args): Statinfo = None with file
(filename, ' rb+ ') as F:data = F.read () If ' "in Data and not args.force: #skip binary file ...?
Print '%s is a binary file?, skip ... '% filename return newdata = convert_line_endings (data, Args.mode) if (data!= newdata): Statinfo = os.stat (filename) if args.keepdate else None f.seek (0) F
. Write (NewData) f.truncate () if Statinfo: Os.utime (filename, (statinfo.st_atime, statinfo.st_mtime)) print filename def walk_dir (d, args): for RO OT, dirs, files in Os.walk (d): for name in Files:convert_file (Os.path.join (root, name), args) If _ _name__ = = ' __main__ ': Import argparse import SYS parser = Argparse.
Argumentparser (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_a Rgument (' 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= ' F Orce ', action= ' store_true ', help= ' force conversion of binary files ') args = Parser.parse_args () if args . Mode = = ' d ': Args.mode = ' W ' if sys.platform = = ' Win32 ' Else ' P ' for filename in args.filename:if os.path.isdir (filename): if args.recursive: Walk_dir (filename, args) Else:print '%s is a directory, skip ... '% filename elif os.path.exi
STS (filename): convert_file (filename, args) Else:print '%s does not exist '% filename