Skip to content

Commit 0f700d4

Browse files
authored
Merge pull request fsspec#660 from limx0/localfile_compression
Add compression to LocalFileOpener
2 parents 61ec18f + 96420fc commit 0f700d4

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

fsspec/implementations/local.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import tempfile
88

99
from fsspec import AbstractFileSystem
10+
from fsspec.compression import compr
11+
from fsspec.core import get_compression
1012
from fsspec.utils import stringify_path
1113

1214

@@ -210,19 +212,25 @@ def make_path_posix(path, sep=os.sep):
210212

211213

212214
class LocalFileOpener(io.IOBase):
213-
def __init__(self, path, mode, autocommit=True, fs=None, **kwargs):
215+
def __init__(
216+
self, path, mode, autocommit=True, fs=None, compression=None, **kwargs
217+
):
214218
self.path = path
215219
self.mode = mode
216220
self.fs = fs
217221
self.f = None
218222
self.autocommit = autocommit
223+
self.compression = get_compression(path, compression)
219224
self.blocksize = io.DEFAULT_BUFFER_SIZE
220225
self._open()
221226

222227
def _open(self):
223228
if self.f is None or self.f.closed:
224229
if self.autocommit or "w" not in self.mode:
225230
self.f = open(self.path, mode=self.mode)
231+
if self.compression:
232+
compress = compr[self.compression]
233+
self.f = compress(self.f, mode=self.mode)
226234
else:
227235
# TODO: check if path is writable?
228236
i, name = tempfile.mkstemp()

fsspec/implementations/tests/test_local.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import absolute_import, division, print_function
22

3+
import bz2
34
import gzip
45
import os
56
import os.path
@@ -662,3 +663,19 @@ def test_transaction(tmpdir):
662663
read_content = fp.read()
663664

664665
assert content == read_content
666+
667+
668+
@pytest.mark.parametrize(
669+
"opener, ext", [(bz2.open, ".bz2"), (gzip.open, ".gz"), (open, "")]
670+
)
671+
def test_infer_compression(tmpdir, opener, ext):
672+
filename = str(tmpdir / f"test{ext}")
673+
content = b"hello world"
674+
with opener(filename, "wb") as fp:
675+
fp.write(content)
676+
677+
fs = LocalFileSystem()
678+
with fs.open(f"file://{filename}", "rb", compression="infer") as fp:
679+
read_content = fp.read()
680+
681+
assert content == read_content

0 commit comments

Comments
 (0)