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="")

你可能感兴趣的:(cat.py)