0

I would like to print both output in Code 3, unfortunately, it doesn't work.

Code 1

with open('file.txt') as f:
    r  = f.read()

print(r)

Output 1

user@linux:~$ python3 script1.py 
line 1
line 2
line 3
user@linux:~$ 

Code 2

with open('file.txt') as f:
    rs = f.read().splitlines()

print(rs)

Output 2

user@linux:~$ python3 script2.py 
['line 1', 'line 2', 'line 3']
user@linux:~$ 

However, when I combine both codes, the second output is missing.

Code 3

with open('file.txt') as f:
    r  = f.read()
    rs = f.read().splitlines()

print(r)
print(rs)

Output 3

user@linux:~$ python3 script3.py 
line 1
line 2
line 3
[]
user@linux:~$ 

Why this code behave this way and how to print both of them?

  • 3
    Once your stream is read, the cursor is at the end of the file so your second instruction do nothing. `rs = r.splitlines()` could work. – Dorian B Apr 15 '20 at 09:58

2 Answers2

1

Because the pointer is now at the end of the file, so there's nothing left to read for that open file.

You can use seek to go to any position of the file.

import os

...

file.seek(0, os.SEEK_SET)  # go to the beginning of the file.


print(file.tell()) # 0

file.seek(0, os.SEEK_END)  # go to the end of the file.



Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
0

When you read a file you cursor is at the end of the file . With the help of seek you can start at index[0] again

with open('file.txt') as f:
    r  = f.read()
    f.seek(0)
    rs = f.read().splitlines()

print(r)
print(rs)
manish
  • 302
  • 2
  • 15