将 bytes 可迭代对象转换为 str 可迭代对象,其中每个值都是一行

2023-11-26

我有一个可迭代的bytes, 例如

bytes_iter = (
    b'col_1,',
    b'c',
    b'ol_2\n1',
    b',"val',
    b'ue"\n',
)

(但通常这会not是硬编码的或一次性可用的,但由生成器提供),我想将其转换为可迭代的str行,其中换行符预先未知,但可以是任何\r, \n or \r\n。所以在这种情况下将是:

lines_iter = (
    'col_1,col_2',
    '1,"value"',
)

(但同样,就像可迭代一样,而不是一次性全部存储在内存中)。

我怎样才能做到这一点?

上下文:我的目标是将 str 行的可迭代传递给csv.reader(我think需要整行?),但我一般对这个答案感兴趣。


Use the io模块为您完成大部分工作:

class ReadableIterator(io.IOBase):
    def __init__(self, it):
        self.it = iter(it)
    def read(self, n):
        # ignore argument, nobody actually cares
        # note that it is *critical* that we suppress the `StopIteration` here
        return next(self.it, b'')
    def readable(self):
        return True

然后就打电话io.TextIOWrapper(ReadableIterator(some_iterable_of_bytes)).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 bytes 可迭代对象转换为 str 可迭代对象,其中每个值都是一行 的相关文章

随机推荐