分行符號轉換指令碼(Python)

來源:互聯網
上載者:User

似乎,需要整理整理使用的python的指令碼了:

很簡單的一個東西,在'\n'、'\r\n'、'\r'3中分行符號之間進行轉換。

用法

usage: eol_convert.py [-h] [-r] [-m {u,p,w,m,d}] [-k] [-f]                      filename [filename ...]Convert Line Endingpositional arguments:  filename        file namesoptional 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

源碼

這隻能算是argparse模組和os模組的utime()、stat()、walk()的一個簡單的練習。可以用,但還相當不完善。

#!/usr/bin/env python#2009-2011 dbzhang800import osimport reimport os.pathdef convert_line_endings(temp, mode):    if mode in ['u', 'p']: #unix, posix        temp = temp.replace('\r\n', '\n')        temp = temp.replace('\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 tempdef convert_file(filename, args):    statinfo = None    with file(filename, 'rb+') as f:        data = f.read()        if '\0' 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 filenamedef walk_dir(d, args):    for root, 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_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 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.exists(filename):            convert_file(filename, args)       else:           print '%s does not exist' % filename

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.