How to write a Python-like program that shows the beginning of the input

Asked 2 years ago, Updated 2 years ago, 17 views

I wrote in Python that the natural number N should be received by a means such as a command line argument, and only the first N line of input should be displayed, but for the time being, I could not deny the feeling.Could you write a little more Python-like?

import sys

i = 0
with open("hightemp.txt", "r") asf:
    where_str=f.readlines()

while(i!=int(sys.argv[1])): 
    print(whole_str[i])
    i+=1

python

2022-09-30 11:01

2 Answers

If there is no problem with readability, you don't have to worry about the details, but you can also write as follows:

import sys

with open("hightemp.txt") as f:
    for i in range(int(sys.argv[1])):
        print(f.readline())


2022-09-30 11:01

import sys
from itertools import islice

n=int(sys.argv[1])
with open("hightemp.txt") as f:
    for line in islice(f,n):
        print(line.rstrip('\n')


2022-09-30 11:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.