python read first n lines of text file code example

Example 1: how to read the first line in a file python

f = open("test.txt", 'r')
variable = f.readline(1)
print(variable)

Example 2: Write a Python program to read first n lines of a file

def read_lines(fname,n,mode='r+'):
	with open(fname) as f:
		for i in range(n):
			print(f.readline())

read_lines('file1.txt',2)
#######################
def readnline(fname,lines,mode='r+'):
	with open(fname) as f:
		li = [ next(f) for i in range(lines)]
	print(li)

readnline('file1.txt',1)

#############################