0

I want to do 10 print of file.read() But, it only gives me 1 line with text and 9 lines with blank text

file = open('text.txt', 'r')
a = 1
while a < 10 :
    print(file.read())
    a = a + 1

output

utzlol
  • 3
  • 1
  • why not store contents in a variable and print it 10 times? `contents = file.read()` and print contents 10 times. – Rahul Apr 23 '19 at 16:25

1 Answers1

2

A file object, once read() will not yield the same text again upon the next read(). You need to rewind the file back to the beginning to make read() work again. Use seek(0)

file = open('text.txt', 'r')
a = 1
while a < 10 :
    print(file.read())
    a = a + 1
    file.seek(0)

If your file contents are not changing between iterations, you can read the contents into a string outside the loop and print that 10 times in the loop.

rdas
  • 20,604
  • 6
  • 33
  • 46