类似于文件对象的BytesIO

7

我不理解这两个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)

然后,在解码方法中循环返回空值。我的理解是BytesIO应该像文件一样的对象,但存储在内存中。那么为什么当我尝试传递文件的一行时,这个循环不返回任何东西,就好像文件中没有行一样呢?

2个回答

10

区别在于流中的当前位置。在第一个示例中,该位置位于开头。但在第二个示例中,它位于结尾。您可以使用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)

StringIO也适用吗? - pippo1980

1
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)

使用 decode(file.getvalue(), 0) :

然后,循环decode方法返回某些内容,不确定是否符合您的期望

也许 decode(file.getvalue().decode('UTF8'), 0) 更好,但还不够完美


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接