or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

data-access.mdfile-operations.mdheader-access.mdindex.mdseismic-unix.mdutilities.md

file-operations.mddocs/

0

# File Operations

1

2

Core functionality for opening existing SEG-Y files, creating new files, and managing file handles. These operations form the foundation of all segyio workflows.

3

4

## Capabilities

5

6

### Opening SEG-Y Files

7

8

Opens existing SEG-Y files for reading or writing with configurable geometry interpretation and endianness handling.

9

10

```python { .api }

11

def open(filename, mode="r", iline=189, xline=193, strict=True, ignore_geometry=False, endian='big'):

12

"""

13

Open a SEG-Y file for reading or writing.

14

15

Parameters:

16

- filename (str): Path to SEG-Y file

17

- mode (str): Access mode ('r' for read-only, 'r+' for read-write)

18

- iline (int or TraceField): Inline header field, default 189

19

- xline (int or TraceField): Crossline header field, default 193

20

- strict (bool): Abort if geometry cannot be inferred, default True

21

- ignore_geometry (bool): Skip geometry building for performance, default False

22

- endian (str): File endianness ('big', 'little', 'msb', 'lsb'), default 'big'

23

24

Returns:

25

SegyFile: File handle for operations

26

27

Raises:

28

IOError: File not found or invalid format

29

ValueError: Invalid geometry or parameters

30

"""

31

```

32

33

**Usage Example:**

34

35

```python

36

# Open file with default settings (structured 3D)

37

with segyio.open('seismic.sgy') as f:

38

print(f.ilines, f.xlines)

39

40

# Open with custom geometry fields

41

with segyio.open('data.sgy', iline=segyio.TraceField.INLINE_3D,

42

xline=segyio.TraceField.CROSSLINE_3D) as f:

43

pass

44

45

# Open unstructured file (faster, no geometry)

46

with segyio.open('shots.sgy', ignore_geometry=True) as f:

47

# Access only by trace number

48

trace = f.trace[0]

49

```

50

51

### Creating SEG-Y Files

52

53

Creates new SEG-Y files with specified geometry and structure using a specification template.

54

55

```python { .api }

56

def create(filename, spec):

57

"""

58

Create a new SEG-Y file with specified structure.

59

60

Parameters:

61

- filename (str): Path for new SEG-Y file

62

- spec (segyio.spec): File structure specification

63

64

Returns:

65

SegyFile: File handle for writing operations

66

67

Raises:

68

IOError: Cannot create file

69

ValueError: Invalid specification

70

"""

71

```

72

73

### File Specification

74

75

Template class for defining the structure and geometry of new SEG-Y files.

76

77

```python { .api }

78

class spec:

79

"""

80

Specification template for creating new SEG-Y files.

81

82

Attributes:

83

- iline (int): Inline header field number, default 189

84

- ilines (array_like): Inline numbers array

85

- xline (int): Crossline header field number, default 193

86

- xlines (array_like): Crossline numbers array

87

- offsets (array_like): Offset numbers array, default [1]

88

- samples (array_like): Sample array (time/depth values)

89

- ext_headers (int): Number of extended text headers, default 0

90

- format (SegySampleFormat): Sample format, default None

91

- sorting (TraceSortingFormat): Trace sorting format, default None

92

- endian (str): File endianness, default 'big'

93

"""

94

```

95

96

**Usage Example:**

97

98

```python

99

import numpy as np

100

101

# Create specification for 3D post-stack volume

102

spec = segyio.spec()

103

spec.samples = np.arange(0, 2000, 4) # 0-2000ms, 4ms sample rate

104

spec.ilines = range(100, 200) # Inlines 100-199

105

spec.xlines = range(300, 400) # Crosslines 300-399

106

spec.format = segyio.SegySampleFormat.IEEE_FLOAT_4_BYTE

107

108

# Create and write file

109

with segyio.create('output.sgy', spec) as f:

110

for i, (il, xl) in enumerate(f.ilines, f.xlines):

111

# Generate or read trace data

112

trace_data = generate_trace(il, xl)

113

f.trace[i] = trace_data

114

115

# Set trace headers

116

f.header[i] = {

117

segyio.TraceField.INLINE_3D: il,

118

segyio.TraceField.CROSSLINE_3D: xl,

119

segyio.TraceField.TRACE_SAMPLE_COUNT: len(spec.samples)

120

}

121

```

122

123

**Pre-stack 4D Example:**

124

125

```python

126

# Create specification for pre-stack data with offsets

127

spec = segyio.spec()

128

spec.samples = np.arange(0, 4000, 2) # 0-4000ms, 2ms sampling

129

spec.ilines = range(1000, 1100, 2) # Every 2nd inline

130

spec.xlines = range(2000, 2200, 2) # Every 2nd crossline

131

spec.offsets = [100, 200, 300, 400, 500] # Offset range

132

133

with segyio.create('prestack.sgy', spec) as f:

134

trace_index = 0

135

for il in spec.ilines:

136

for xl in spec.xlines:

137

for offset in spec.offsets:

138

# Write trace data and headers

139

f.trace[trace_index] = prestack_trace(il, xl, offset)

140

f.header[trace_index] = {

141

segyio.TraceField.INLINE_3D: il,

142

segyio.TraceField.CROSSLINE_3D: xl,

143

segyio.TraceField.offset: offset

144

}

145

trace_index += 1

146

```

147

148

### SegyFile Class

149

150

Main file handle providing access to all SEG-Y file operations and data access modes.

151

152

```python { .api }

153

class SegyFile:

154

"""

155

Main file handle for SEG-Y files.

156

157

Properties:

158

- dtype (numpy.dtype): Data type of traces

159

- sorting (int): Inline or crossline sorting

160

- tracecount (int): Total number of traces

161

- samples (numpy.ndarray): Array of sample indices/times

162

- offsets (numpy.ndarray): Array of offset values

163

- ext_headers (int): Number of extended text headers

164

- unstructured (bool): True if file has no regular geometry

165

- ilines (array_like or None): Inline numbers (structured files)

166

- xlines (array_like or None): Crossline numbers (structured files)

167

- readonly (bool): True if file opened read-only

168

- format: Sample format description

169

- endian: File endianness

170

171

Access Modes:

172

- header: Access to trace headers

173

- trace: Access to trace data

174

- iline: Access by inline number (3D structured)

175

- xline: Access by crossline number (3D structured)

176

- fast: Fast dimension access

177

- slow: Slow dimension access

178

- depth_slice: Access horizontal slices

179

- gather: Access pre-stack gathers

180

- text: Access to textual headers

181

- bin: Access to binary header fields

182

183

Methods:

184

- flush(): Flush pending writes to disk

185

- close(): Close the file handle

186

- mmap(): Memory map the file, returns success status

187

- attributes(field): Get file-wide attribute reading for header field

188

- interpret(ilines, xlines, offsets, sorting): Re-interpret file structure

189

- group(word): Group traces by header field values (experimental)

190

"""

191

```

192

193

**Usage Example:**

194

195

```python

196

with segyio.open('data.sgy') as f:

197

# File properties

198

print(f"Traces: {f.tracecount}")

199

print(f"Sample count: {len(f.samples)}")

200

print(f"Data type: {f.dtype}")

201

print(f"Read-only: {f.readonly}")

202

203

# Check if structured or unstructured

204

if f.unstructured:

205

print("Unstructured file - access by trace index only")

206

else:

207

print(f"Structured: IL {f.ilines[0]}-{f.ilines[-1]}, "

208

f"XL {f.xlines[0]}-{f.xlines[-1]}")

209

210

# Memory map for large files

211

if f.mmap():

212

print("File memory mapped for faster access")

213

214

# Group traces by CDP (experimental feature)

215

cdp_groups = f.group(segyio.TraceField.CDP)

216

print(f"Found {len(cdp_groups)} CDP groups")

217

218

# Get file-wide attributes for a header field

219

cdp_values = f.attributes(segyio.TraceField.CDP)

220

print(f"CDP range: {cdp_values[0]} to {cdp_values[-1]}")

221

```

222

223

## Common Patterns

224

225

### Context Management

226

227

Always use context managers for proper resource cleanup:

228

229

```python

230

# Correct - automatically closes file

231

with segyio.open('file.sgy') as f:

232

data = f.trace[0]

233

234

# Also correct for explicit control

235

f = segyio.open('file.sgy')

236

try:

237

data = f.trace[0]

238

finally:

239

f.close()

240

```

241

242

### Error Handling

243

244

```python

245

try:

246

with segyio.open('data.sgy') as f:

247

# File operations

248

pass

249

except IOError as e:

250

print(f"File error: {e}")

251

except ValueError as e:

252

print(f"Invalid parameters: {e}")

253

```