Answer to Question #304923 in Python for Sudheer

Question #304923

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 !

1
Expert's answer
2022-03-02T08:20:14-0500
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):

>>>


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS