EltraEden
EltraEden

Reputation: 111

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?

Upvotes: 7

Views: 10934

Answers (2)

pippo1980
pippo1980

Reputation: 3096

import io
from itertools import islice


def decode(file, lines):
   for line in islice(file, lines, None):
      print(line)

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

with decode(file.getvalue(), 0) :

Then loop in decode method returns something, not sure it is what you were expecting

possibly decode(file.getvalue().decode('UTF8'), 0) gets better but not quite it

Upvotes: 1

Plaváček
Plaváček

Reputation: 143

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)

Upvotes: 10

Related Questions