Skip to content

add **encoding** argument in netCDF4 backend #10372

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions xarray/backends/netCDF4_.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import functools
import operator
import os
import sys
from collections.abc import Iterable
from contextlib import suppress
from typing import TYPE_CHECKING, Any
Expand Down Expand Up @@ -371,7 +372,13 @@ class NetCDF4DataStore(WritableCFDataStore):
)

def __init__(
self, manager, group=None, mode=None, lock=NETCDF4_PYTHON_LOCK, autoclose=False
self,
manager,
group=None,
mode=None,
lock=NETCDF4_PYTHON_LOCK,
autoclose=False,
encoding=None,
):
import netCDF4

Expand All @@ -391,7 +398,7 @@ def __init__(
self._group = group
self._mode = mode
self.format = self.ds.data_model
self._filename = self.ds.filepath()
self._filename = self.ds.filepath(encoding=encoding)
self.is_remote = is_remote_uri(self._filename)
self.lock = ensure_lock(lock)
self.autoclose = autoclose
Expand All @@ -410,6 +417,7 @@ def open(
lock=None,
lock_maker=None,
autoclose=False,
encoding=None,
):
import netCDF4

Expand All @@ -422,6 +430,9 @@ def open(
"with engine='scipy' or 'h5netcdf'"
)

if encoding is None:
encoding = sys.getfilesystemencoding()

if format is None:
format = "NETCDF4"

Expand All @@ -443,13 +454,21 @@ def open(
diskless=diskless,
persist=persist,
format=format,
encoding=encoding,
)
if auto_complex is not None:
kwargs["auto_complex"] = auto_complex
manager = CachingFileManager(
netCDF4.Dataset, filename, mode=mode, kwargs=kwargs
)
return cls(manager, group=group, mode=mode, lock=lock, autoclose=autoclose)
return cls(
manager,
group=group,
mode=mode,
lock=lock,
autoclose=autoclose,
encoding=encoding,
)

def _acquire(self, needs_lock=True):
with self._manager.acquire_context(needs_lock) as root:
Expand Down Expand Up @@ -661,6 +680,7 @@ def open_dataset(
auto_complex=None,
lock=None,
autoclose=False,
encoding=None,
) -> Dataset:
filename_or_obj = _normalize_path(filename_or_obj)
store = NetCDF4DataStore.open(
Expand All @@ -674,6 +694,7 @@ def open_dataset(
auto_complex=auto_complex,
lock=lock,
autoclose=autoclose,
encoding=encoding,
)

store_entrypoint = StoreBackendEntrypoint()
Expand Down
Loading