1

I want to write a string to a StringIO() object and then read it line by line; I tried two ways and none of them produced any output. What am I doing wrong?

Creating object, writing to it and check if it worked:

from io import StringIO
temp=StringIO()
temp.write("This is a \n test sentence\n!")
temp.getvalue() --> 'This is a \n test sentence\n!'

Approach one:

for line in temp:
    print(line)

Approach two:

test = True
while test:
    line = temp.readline()
    if not line:
         test=False
    else:
         print(line)
LizzAlice
  • 678
  • 7
  • 18

1 Answers1

2

You have to change the (seek) stream position to the byte offset 0. You can also use tell to get the current stream position.

>>> from io import StringIO
>>> temp = StringIO()
>>> temp.write("This is a \n test sentence\n!")
27
>>> temp.tell() # current stream position.
27
>>> temp.seek(0) # Change the stream position to the byte offset `0`
0
>>> for line in temp:
...     print(line)
...
This is a

 test sentence

!
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • Thank you, that solved it! – LizzAlice Sep 29 '21 at 09:04
  • 2
    When you use the `.write()` method to write to the stream, the stream position will indicate the end of the stream. To reset the stream indicator position to the start of the stream, you can read the string into `StringIO` directly: `from io import StringIO; temp = StringIO("This is a \n test sentence\n!");lines = [line for line in temp]; print(lines)` – psychemedia Sep 29 '21 at 09:18