Skip to main content
 首页 » 编程设计

python之BytesIO 类文件对象

2024年12月31日7lhb25

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