Sunday, 27 January 2019

encodings.utf_8.StreamReader readline(), read() and seek() don't cooperate

Consider this very simple example.

import codecs
from io import BytesIO

string = b"""# test comment
Some line without comment
# another comment
"""

reader = codecs.getreader("UTF-8")
stream = reader(BytesIO(string))

lines = []
while True:
    # get current position
    position = stream.tell()

    # read first character
    char = stream.read(1)

    # return cursor to start
    stream.seek(position, 0)

    # end of stream
    if char == "":
        break

    # line is not comment
    if char != "#":
        lines.append(stream.readline())
        continue

    # line is comment. Skip it.
    stream.readline()

print(lines)
assert lines == ["Some line without comment\n"]

I am trying to read line by line from StreamReader and if the line starts with # i skip it otherwise I store it in a list. But there is some strange behaviour when I use seek() method. It seems like seek() and readline() don't cooperate and move cursor somewhere far away. The result list is empty.

Of course I could do it in different way. But as I wrote above this is a very simple example and it helps me understand how things work together.

I use Python 3.5



from encodings.utf_8.StreamReader readline(), read() and seek() don't cooperate

No comments:

Post a Comment