HxUtils.convert_endlines_for_dir: 批量转换换行符

python学习网 2018-02-11 12:18:01

在 windows 和 linux 系统,换行符有时需要转换,其代码文件 HxUntils.py 如下:

 ''' HxUtils.py 2018 by x01 '''

import os, sys

def convert_endlines(filepath, tounix=True):
    try:
        oldfile = open(filepath, 'rb+')
        path, name = os.path.split(filepath)
        newfile = open(path + '$' + name, 'ba+')

        old = b'\r'
        new = b''
        if not tounix:
            old = b'\n'
            new = b'\r\n'

        while True:
            olddata = oldfile.read(1024)
            newdata = olddata.replace(old, new)
            newfile.write(newdata)
            if len(olddata) < 1024:
                break
            
        newfile.close()
        oldfile.close()

        os.remove(filepath)
        os.rename(path + '$' + name, filepath)

    except IOError as e:
        print(e)

def convert_endlines_for_dir():
    dirpath, tounix, extname = ('.', True, '.py')
    if len(sys.argv) == 2:
        dirpath = sys.argv[1]
    elif len(sys.argv) == 3:
        dirpath, tounix = (sys.argv[1], sys.argv[2])
    elif len(sys.argv) == 4:
        dirpath, tounix, extname = (sys.argv[1], sys.argv[2], sys.argv[3])

    for (thisdir, subshere, fileshere) in os.walk(dirpath):
        for filename in fileshere:
            if filename.endswith(extname):
                #print(os.path.join(thisdir,filename))
                convert_endlines(os.path.join(thisdir,filename), tounix)

if __name__ == '__main__':
    convert_endlines_for_dir()
    

使用方法如下:

$ python3 HxUntils.py  [dirpath tounix extname]

 

阅读(751) 评论(0)