Mic*_*mza 8 python csv newline
我有一个可迭代的bytes,例如
bytes_iter = (
b'col_1,',
b'c',
b'ol_2\n1',
b',"val',
b'ue"\n',
)
Run Code Online (Sandbox Code Playgroud)
(但通常这不会被硬编码或一次性全部可用,而是由生成器提供)并且我想将其转换为可迭代的str行,其中换行符预先未知,但可以是\r,\n或中的任何一个\r\n。所以在这种情况下将是:
bytes_iter = (
b'col_1,',
b'c',
b'ol_2\n1',
b',"val',
b'ue"\n',
)
Run Code Online (Sandbox Code Playgroud)
(但同样,就像可迭代一样,而不是一次性全部存储在内存中)。
我怎样才能做到这一点?
上下文:我的目标是将 str 行的可迭代传递给csv.reader(我认为需要整行?),但我一般对这个答案感兴趣。
使用该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
Run Code Online (Sandbox Code Playgroud)
然后就打电话吧io.TextIOWrapper(ReadableIterator(some_iterable_of_bytes))。
| 归档时间: |
|
| 查看次数: |
1029 次 |
| 最近记录: |