且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取Python中文本文件的换行统计

更新时间:2023-02-20 11:00:15

import sys


def calculate_line_endings(path):
    # order matters!
    endings = [
        b'\r\n',
        b'\n\r',
        b'\n',
        b'\r',
    ]
    counts = dict.fromkeys(endings, 0)

    with open(path, 'rb') as fp:
        for line in fp:
            for x in endings:
                if line.endswith(x):
                    counts[x] += 1
                    break
    print(counts)


if __name__ == '__main__':
    if len(sys.argv) == 2:
        calculate_line_endings(sys.argv[1])

    sys.exit('usage: %s <filepath>' % sys.argv[0])

为您的文件提供输出

crlf: 1123
lfcr: 0
cr: 0
lf: 0

够了吗?