CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-h5netcdf

netCDF4 file access via h5py with hierarchical and legacy APIs for scientific computing

69

0.83x
Overview
Eval results
Files

file-operations.mddocs/

File Operations

Core file management functionality for opening, creating, and managing netCDF4 files. The File class serves as the entry point for all netCDF4 operations and provides context manager support for automatic resource cleanup.

Capabilities

File Creation and Opening

Open or create netCDF4 files with various access modes and configuration options.

class File(Group):
    def __init__(self, path, mode: str = "r", invalid_netcdf: bool = False, 
                 phony_dims: str = None, track_order: bool = None,
                 decode_vlen_strings: bool = False, **kwargs):
        """
        Open or create a netCDF4 file.
        
        Args:
            path: Path to the netCDF4 file, h5py File object, or file-like object
            mode (str): File access mode - "r" (read), "r+" (read/write), 
                       "a" (append), "w" (write/create)
            invalid_netcdf (bool): Allow features not compatible with netCDF4 standard
            phony_dims (str): Handle for unlabeled dimensions - "sort" or "access"
            track_order (bool): Track creation order (auto-detected based on h5py version)
            decode_vlen_strings (bool): Automatically decode variable-length strings
            **kwargs: Additional HDF5 file creation parameters
        """
        ...

File Properties

Access file metadata and configuration settings.

@property
def filename(self) -> str:
    """Path to the file."""
    ...

@property
def mode(self) -> str:
    """File access mode."""
    ...

@property
def parent(self) -> None:
    """Always None for File objects (root level)."""
    ...

@property
def _closed(self) -> bool:
    """Whether the file is closed."""
    ...

File Management

Save changes and close files with proper resource cleanup.

def close(self) -> None:
    """Close the file and release resources."""
    ...

def flush(self) -> None:
    """Flush pending changes to disk."""
    ...

def sync(self) -> None:
    """Alias for flush() - synchronize file with disk."""
    ...

Context Manager Support

Automatic resource management using Python's with statement.

def __enter__(self) -> File:
    """Enter the runtime context."""
    ...

def __exit__(self, exc_type, exc_val, exc_tb) -> None:
    """Exit the runtime context and close the file."""
    ...

Usage Examples

Basic File Operations

import h5netcdf

# Read-only access
with h5netcdf.File('data.nc', 'r') as f:
    print(f"File mode: {f.mode}")
    print(f"File path: {f.filename}")
    # File automatically closed when exiting context

# Create new file
with h5netcdf.File('new_data.nc', 'w') as f:
    # Create dimensions and variables
    f.dimensions['time'] = 10
    temp = f.create_variable('temperature', ('time',), dtype='f4')

# Append to existing file
with h5netcdf.File('existing.nc', 'a') as f:
    # Add new variables or modify existing ones
    if 'humidity' not in f.variables:
        humidity = f.create_variable('humidity', ('time',), dtype='f4')

Advanced Configuration

# Enable non-standard netCDF features
with h5netcdf.File('custom.nc', 'w', invalid_netcdf=True) as f:
    # Can use HDF5 features not in netCDF4 standard
    pass

# Handle unlabeled dimensions
with h5netcdf.File('unlabeled.nc', 'r', phony_dims='sort') as f:
    # Dimensions without coordinate variables are handled consistently
    pass

# Disable string decoding for performance
with h5netcdf.File('binary_strings.nc', 'r', decode_vlen_strings=False) as f:
    # String variables returned as bytes instead of decoded strings
    pass

Error Handling

try:
    with h5netcdf.File('nonexistent.nc', 'r') as f:
        pass
except FileNotFoundError:
    print("File not found")

try:
    with h5netcdf.File('readonly.nc', 'w') as f:
        pass
except PermissionError:
    print("Permission denied")

File Access Modes

  • "r": Read-only access (default)
  • "r+": Read-write access to existing file
  • "a": Append mode - read-write access, create if doesn't exist
  • "w": Write mode - create new file, overwrite if exists

HDF5 Integration

h5netcdf files are fully compatible HDF5 files that can be opened with h5py or other HDF5 tools:

import h5netcdf
import h5py

# Create with h5netcdf
with h5netcdf.File('test.nc', 'w') as f:
    f.dimensions['x'] = 10
    var = f.create_variable('data', ('x',), dtype='i4')
    var[:] = range(10)

# Read with h5py
with h5py.File('test.nc', 'r') as f:
    data = f['data'][:]  # Direct HDF5 access

Install with Tessl CLI

npx tessl i tessl/pypi-h5netcdf

docs

attributes.md

dimensions.md

file-operations.md

groups.md

index.md

legacy-api.md

user-types.md

variables.md

tile.json