Python 类字节文件对象

Python 类字节文件对象,python,bytesio,Python,Bytesio,我无法理解这两个BytesIO对象的区别。 如果我这样做: f = open('decoder/logs/testfile.txt', 'rb') file = io.BytesIO(f.read()) decode(file,0) 然后,在解码方法中,这起作用: for line in islice(file, lines, None): 但如果我像这样创建BytesIO: file = io.BytesIO() file.write(b"Some codded message") dec

我无法理解这两个BytesIO对象的区别。 如果我这样做:

f = open('decoder/logs/testfile.txt', 'rb')
file = io.BytesIO(f.read())
decode(file,0)
然后,在解码方法中,这起作用:

for line in islice(file, lines, None):
但如果我像这样创建BytesIO:

file = io.BytesIO()
file.write(b"Some codded message")
decode(file, 0)
然后,decode方法中的循环不返回任何内容。
我的理解是BytesIO应该像文件一样充当对象,但存储在内存中。那么,为什么当我尝试只传递一行文件时,这个循环不会像文件中没有行一样返回任何内容呢?

区别在于流中的当前位置。在第一个示例中,位置位于开头。但在第二个例子中,它是在最后。您可以使用
file.tell()
获取当前位置,然后通过
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)