0

I want my simple python program to go to a text file and collect 5 lines to print out.

I have got this far but it returns the whole file which I don't want to do yet.

file=open('IH.txt','r')
text = file.read()
print(text)
file.close()

Can anyone help?

3
  • Why don't you open a file using return and increment the counter variable by one. In case the counter reaches 5 do return. Commented Oct 22, 2017 at 9:36
  • 1
    go through https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files Commented Oct 22, 2017 at 9:36
  • Vidya, I'm a complete novice and don't know what 'return' is Commented Oct 22, 2017 at 9:48

1 Answer 1

2

How about

file=open('IH.txt','r')
text=""
for i in range(6):
    text += file.readLine()
print(text)
file.close()

read() reads the entire file. readline() reads only a line.

The loop has 5 iterations and in each iteration, the next line from the file is appended to text via concatenation.

You might also want to do exception handling.

Sign up to request clarification or add additional context in comments.

5 Comments

for i in range(6): text += file.readline #this works, thank you
Actually, that is repeating in each iteration like you say, I just want it to print 5 lines in one go then stop, I later want to print the next 5 lines and stop again. Any idea?
@UKcodeNovice What do you want to do after reading the lines? Would it be okay to make the lines as a list?
I want to ask a question about the lines
@UKcodeNovice Have a look at islice from itertools package. But even that is a form of loop it seems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.