Topics covered

Python

Sunday, 25 October 2020

How To Print First 'N' Lines Of A File In Python

 In this post we will see how to read first 'N' lines from a .txt file and display it in Python.

To achieve that, first we will consider a "Sample.txt" file which contains the following lines:

Sample.txt:

This is a program to display n lines in python.

In this program we will use readline and range function 

Python is a interpreted and widely use high level programming language


Function To Display Or Print Lines From .Txt File:


#function to print lines in Python
def read_n_lines():
N = 2 #variable to space range of lines to display or print

#open file in read mode
with open("temp.txt", "r") as file:
for i in range(N):
print(file.readline())
file.close()

 So the output of this function will print first two lines of this Sample.txt file as we have specified the range in varaible as N=2

Output:

This is a program to display n lines in python.

In this program we will use readline and range function.

Full Code:


#function to print lines in Python
def read_n_lines():
N = 2 #variable to space range of lines to display or print

#open file in read mode
with open("temp.txt", "r") as file:
for i in range(N):
print(file.readline())
file.close()


#main calling function

def main():
read_n_lines()


if __name__ == '__main__':
main()

No comments:

Post a Comment