You are given a file read.txt which contains some lines. As a python developer, you need to write a python function Read_Contents(fname, n) (Refer RollNo_W11A_1.py )which takes the name of the files and number of lines to be read from file. The function returns those lines in a string as shown in example.
Contents of read.txt file will be like:
This is python Lab.
The is the program for file handling.
Reading first n lines !
def Read_Contents(fname, n):
file = open(fname,"r")
s = (file.read()).split("\n")
if(n > len(s)):
n = len(s)
for u in range(0,n):
print("Line #",u+1,":\t",s[u])
Read_Contents("H:\\Read.txt",5)
Python Output:
Line # 1 : from math import sqrt
Line # 2 : n = 1
Line # 3 : prime_flag = 0
Line # 4 : if(n > 1):
Line # 5 : for i in range(2, int(sqrt(n)) + 1):
>>>
Comments
Leave a comment