首页 > 解决方案 > 如何在python中以N为参数打印文件的前N行

问题描述

我将如何在 python 中获取文本文件的前 N ​​行?N 必须作为论据

用法:

python file.py datafile -N 10

我的代码

import sys
from itertools import islice

args = sys.argv
print (args)
if args[1] == '-h':
    print ("-N for printing the number of lines: python file.py datafile -N 10")

if args[-2] == '-N':
    datafile = args[1]
    number = int(args[-1])
    with open(datafile) as myfile:
        head = list(islice(myfile, number))
        head = [item.strip() for item in head]

        print (head)
        print ('\n'.join(head))

我写了程序,可以让我比这段代码更了解

标签: pythonarguments

解决方案


假设您实现的 print_head 逻辑不需要更改,这是我认为您正在寻找的脚本:

import sys
from itertools import islice

def print_head(file, n):
    if not file or not n:
        return

    with open(file) as myfile:
        head = [item.strip() for item in islice(myfile, n)]

    print(head)

def parse_args():
    result = {'script': sys.argv[0]}
    args = iter(sys.argv)
    for arg in args:
        if arg == '-F':
            result['filename'] = next(args)

        if arg == '-N':
            result['num_lines'] = int(next(args))

    return result

if __name__ == '__main__':
    script_args = parse_args()
    print_head(script_args.get('filename', ''), script_args.get('num_lines', 0))

运行脚本

python file.py -F datafile -N 10

注意:实现它的最佳方法是使用argparse


推荐阅读