简体   繁体   中英

How to print first n line from the argument passed file with arg parser library

How to print N line from the argument passed as file with arg parser library.

I have a file with 100 lines. I want to print the first n lines. I need to use argparser also since i don't want to edit the file inside the python script

In the script below N is is the first N number of lines to print. Need to give that also as argument

import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
args = parser.parse_args()

with open("filename") as myfile:
    head = [next(filename) for x in range(N)]
print (head)

My usage

python file.py file.txt -c 10

It will print first 10 lines from the file.

In my opinion you should add another argparse argument. Something like:



import argparse
parser = argparse.ArgumentParser(description='print n lines')
parser.add_argument('filename',type=argparse.FileType('r'), help='Path to file name')
parser.add_argument('--n_lines',type='int', help='Number of line to print')
args = parser.parse_args()


with open(args.filename) as myfile:
    head = [next(myfile) for x in range(args.n_lines)]
print (head)

Loop through the lines in the file by doing this

with open("file.txt") as myfile:
    lines = myfile.readlines()
    for line in lines[0:10]:
         print(line)

This will print the first 10 lines, so lines 0 to 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM