Adapt an iterator to behave like a file-like object in Python

前端 未结 8 1152
Happy的楠姐
Happy的楠姐 2020-12-13 07:00

I have a generator producing a list of strings. Is there a utility/adapter in Python that could make it look like a file?

For example,

>>> d         


        
8条回答
  •  一个人的身影
    2020-12-13 07:40

    The problem with StringIO is that you have to load everything into the buffer up front. This can be a problem if the generator is infinite :)

    from itertools import chain, islice
    class some_magic_adaptor(object):
        def __init__(self, src):
            self.src = chain.from_iterable(src)
        def read(self, n):
            return "".join(islice(self.src, None, n))
    

提交回复
热议问题