1

I have the code below:

>>> from pathlib import Path
>>> path = Path(r"C:\Users\slash\test.txt")
>>> f = path.open(encoding="utf-8")
>>> f
<_io.TextIOWrapper name="C:\\Users\\slash\\test.txt" mode='r' encoding='utf-8'>
>>> f.read()
'Test line 1\nTest line 2\nTest line 3\n'
>>> f.read()
''

Can you guys explain to me the behavior here - it looks like TextIOWrapper can only be read once?

Is there away to read it multiple times until I'm done?

Thank you.

>>> from pathlib import Path
>>> path = Path(r"C:\Users\slash\test.txt")
>>> f = path.open(encoding="utf-8")
>>> f
<_io.TextIOWrapper name="C:\\Users\\slash\\test.txt" mode='r' encoding='utf-8'>
>>> f.read()
'Test line 1\nTest line 2\nTest line 3\n'
>>> f.read()
''

I'm expecting _io.TextIOWrapper can be read multiple times

tdan
  • 13
  • 2

1 Answers1

1
>>> f.read()
'Test line 1\nTest line 2\nTest line 3\n'
>>> f.read()
''

Imagine your f object is nothing but a cursor. Once the cursor has ended readinig the file, you have to retake it to the beginning.

You can do this using the method seek with arguments (0, 0).

>>> f.read()
'Test line 1\nTest line 2\nTest line 3\n'
>>> f.seek(0,0)
>>> f.read()
'Test line 1\nTest line 2\nTest line 3\n'
FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28