1

My question: Program to read first n lines from a txt file,get n as user input. I tried this,

f1=open('sampletest.txt','r')
n=int(input("Enter number of lines to be read from the txt file:"))
line=f1.readlines(n)
print(line)
f1.close()

My txtfile contents which I named sampletest are as follows:

Tom and Jerry are cartoon characters.

Tom is a cat.

Jerry is a mouse.

They have a common friend,Spike.

Spike is a dog.

The output I get by executing my python code: Enter number of lines to be read from the txt file:3 ['Tom and Jerry are cartoon characters.\n']

How can I correct my code?I am new to coding. Please help. Thanks in advance.

  • 1
    In ```readlines(n)```, the ```n``` indicates the number of bytes and not the number of lines. – Sanil Mar 29 '20 at 13:47

1 Answers1

0
f1=open('sampletest.txt','r')
n=int(input("Enter number of lines to be read from the txt file:"))
line = ''.join(f1.readline() for _ in range(n))
print(line)
f1.close()

your code not working because readlines accepts hint parameter instead of lines count to read