cat.py

import argparse

parser = argparse.ArgumentParser(description="Output the contents of the files to the screen")
parser.add_argument("file_names", nargs='+', help="The filenames split by blank")
parser.add_argument("-n", "--numbers", action="store_true", help="Print line numbers")
parser.add_argument("--output", "->", help="Output to a new file")
# parser.add_argument("-o", "--output", help="Output to a new file")
args = parser.parse_args()

cat_contents = []
line_number = 1

for file_name in args.file_names:
    with open(file_name) as fp:
        line_string = fp.readline().strip()
        while line_string:
            contents = '{}\t'.format(line_number) if args.numbers else ""
            contents += line_string
            line_number += 1
            cat_contents.append(contents)
            line_string = fp.readline().strip()
cat_contents = '\n'.join(cat_contents)

if args.output:
    with open(args.output, 'w', encoding='utf-8') as fp:
        fp.write(cat_contents)
else:
    print(cat_contents, end="")
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。