or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

attributes.mddimensions.mdfile-operations.mdgroups.mdindex.mdlegacy-api.mduser-types.mdvariables.md

file-operations.mddocs/

0

# File Operations

1

2

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.

3

4

## Capabilities

5

6

### File Creation and Opening

7

8

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

9

10

```python { .api }

11

class File(Group):

12

def __init__(self, path, mode: str = "r", invalid_netcdf: bool = False,

13

phony_dims: str = None, track_order: bool = None,

14

decode_vlen_strings: bool = False, **kwargs):

15

"""

16

Open or create a netCDF4 file.

17

18

Args:

19

path: Path to the netCDF4 file, h5py File object, or file-like object

20

mode (str): File access mode - "r" (read), "r+" (read/write),

21

"a" (append), "w" (write/create)

22

invalid_netcdf (bool): Allow features not compatible with netCDF4 standard

23

phony_dims (str): Handle for unlabeled dimensions - "sort" or "access"

24

track_order (bool): Track creation order (auto-detected based on h5py version)

25

decode_vlen_strings (bool): Automatically decode variable-length strings

26

**kwargs: Additional HDF5 file creation parameters

27

"""

28

...

29

```

30

31

### File Properties

32

33

Access file metadata and configuration settings.

34

35

```python { .api }

36

@property

37

def filename(self) -> str:

38

"""Path to the file."""

39

...

40

41

@property

42

def mode(self) -> str:

43

"""File access mode."""

44

...

45

46

@property

47

def parent(self) -> None:

48

"""Always None for File objects (root level)."""

49

...

50

51

@property

52

def _closed(self) -> bool:

53

"""Whether the file is closed."""

54

...

55

```

56

57

### File Management

58

59

Save changes and close files with proper resource cleanup.

60

61

```python { .api }

62

def close(self) -> None:

63

"""Close the file and release resources."""

64

...

65

66

def flush(self) -> None:

67

"""Flush pending changes to disk."""

68

...

69

70

def sync(self) -> None:

71

"""Alias for flush() - synchronize file with disk."""

72

...

73

```

74

75

### Context Manager Support

76

77

Automatic resource management using Python's with statement.

78

79

```python { .api }

80

def __enter__(self) -> File:

81

"""Enter the runtime context."""

82

...

83

84

def __exit__(self, exc_type, exc_val, exc_tb) -> None:

85

"""Exit the runtime context and close the file."""

86

...

87

```

88

89

## Usage Examples

90

91

### Basic File Operations

92

93

```python

94

import h5netcdf

95

96

# Read-only access

97

with h5netcdf.File('data.nc', 'r') as f:

98

print(f"File mode: {f.mode}")

99

print(f"File path: {f.filename}")

100

# File automatically closed when exiting context

101

102

# Create new file

103

with h5netcdf.File('new_data.nc', 'w') as f:

104

# Create dimensions and variables

105

f.dimensions['time'] = 10

106

temp = f.create_variable('temperature', ('time',), dtype='f4')

107

108

# Append to existing file

109

with h5netcdf.File('existing.nc', 'a') as f:

110

# Add new variables or modify existing ones

111

if 'humidity' not in f.variables:

112

humidity = f.create_variable('humidity', ('time',), dtype='f4')

113

```

114

115

### Advanced Configuration

116

117

```python

118

# Enable non-standard netCDF features

119

with h5netcdf.File('custom.nc', 'w', invalid_netcdf=True) as f:

120

# Can use HDF5 features not in netCDF4 standard

121

pass

122

123

# Handle unlabeled dimensions

124

with h5netcdf.File('unlabeled.nc', 'r', phony_dims='sort') as f:

125

# Dimensions without coordinate variables are handled consistently

126

pass

127

128

# Disable string decoding for performance

129

with h5netcdf.File('binary_strings.nc', 'r', decode_vlen_strings=False) as f:

130

# String variables returned as bytes instead of decoded strings

131

pass

132

```

133

134

### Error Handling

135

136

```python

137

try:

138

with h5netcdf.File('nonexistent.nc', 'r') as f:

139

pass

140

except FileNotFoundError:

141

print("File not found")

142

143

try:

144

with h5netcdf.File('readonly.nc', 'w') as f:

145

pass

146

except PermissionError:

147

print("Permission denied")

148

```

149

150

## File Access Modes

151

152

- **"r"**: Read-only access (default)

153

- **"r+"**: Read-write access to existing file

154

- **"a"**: Append mode - read-write access, create if doesn't exist

155

- **"w"**: Write mode - create new file, overwrite if exists

156

157

## HDF5 Integration

158

159

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

160

161

```python

162

import h5netcdf

163

import h5py

164

165

# Create with h5netcdf

166

with h5netcdf.File('test.nc', 'w') as f:

167

f.dimensions['x'] = 10

168

var = f.create_variable('data', ('x',), dtype='i4')

169

var[:] = range(10)

170

171

# Read with h5py

172

with h5py.File('test.nc', 'r') as f:

173

data = f['data'][:] # Direct HDF5 access

174

```