Consider the following code that depends on zstandard
library from pip:
import zstandard
import contextlib
old_open = open
@contextlib.contextmanager
def open(*, fileobj=None, file=None, mode='r'):
if mode not in ('r', 'w'):
raise ValueError('Mode should be "r" or "w")')
if not fileobj and not file:
raise ValueError('either fileobj or file must be provided')
if mode == "r":
cctx = zstandard.ZstdDecompressor()
if file:
with old_open(file, 'rb') as fh, cctx.stream_reader(fh) as reader:
yield reader
else:
yield cctx.stream_reader(fileobj)
elif mode == "w":
cctx = zstandard.ZstdCompressor()
if file:
with old_open(file, 'wb') as fh, cctx.stream_writer(fh) as writer:
yield writer
else:
yield cctx.stream_writer(fileobj)
if __name__ == '__main__':
import io
with open(file='/tmp/a.zst', mode='w') as f:
f.write(b'asd')
with open(file='/tmp/a.zst', mode='r') as f:
for line in f:
print(line)
I'm getting the following error:
Traceback (most recent call last):
File "zstdopen.py", line 35, in <module>
for line in f:
io.UnsupportedOperation
Given that read() is already there and works, is there a way to wrap this in an interface that would automatically provide readline() for me?