Search code examples
pythonbytesio

BytesIO like file object


I can't understand the difference of these two BytesIO objects. If i do this :

f = open('decoder/logs/testfile.txt', 'rb')
file = io.BytesIO(f.read())
decode(file,0)

then in decode method this works :

for line in islice(file, lines, None):

But if i create BytesIO like this :

file = io.BytesIO()
file.write(b"Some codded message")
decode(file, 0)

Then loop in decode method returns nothing. What i understand is BytesIO should act as file like object but stored in memory. So why when i try to pass only one line of file this loop return nothing like there was no lines in file?


Solution

  • The difference is the current position in the stream. In the first example, the position is at the beginning. But in the second example, it is at the end. You can obtain the current position using file.tell() and return back to the start by file.seek(0):

    import io
    from itertools import islice
    
    
    def decode(file, lines):
       for line in islice(file, lines, None):
          print(line)
    
    
    f = open('testfile.txt', 'rb')
    file = io.BytesIO(f.read())
    print(file.tell())  # The position is 0
    decode(file, 0)
    
    
    file = io.BytesIO()
    file.write(b"Some codded message")
    print(file.tell())  # The position is 19
    decode(file, 0)
    
    file = io.BytesIO()
    file.write(b"Some codded message")
    file.seek(0)
    print(file.tell())  # The position is 0
    decode(file, 0)