or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

file-operations.mdheader-operations.mdimage-operations.mdindex.mdtable-operations.md

file-operations.mddocs/

0

# File Operations

1

2

Core FITS file handling functionality providing both high-level convenience functions for simple operations and the FITS class for complete control over file operations, HDU management, and advanced workflows.

3

4

## Capabilities

5

6

### FITS Class

7

8

The primary interface for reading and writing FITS files with full control over HDU operations, file modes, and advanced features.

9

10

```python { .api }

11

class FITS:

12

def __init__(self, filename, mode='r', lower=False, upper=False,

13

trim_strings=False, vstorage='fixed', case_sensitive=False,

14

iter_row_buffer=1, write_bitcols=False, ignore_empty=False,

15

verbose=False, clobber=False):

16

"""

17

Open a FITS file for reading and/or writing.

18

19

Parameters:

20

- filename: str, path to FITS file

21

- mode: str, file access mode ('r', 'rw', 'r+')

22

- lower: bool, convert column names to lowercase

23

- upper: bool, convert column names to uppercase

24

- trim_strings: bool, remove trailing whitespace from strings

25

- vstorage: str, variable length storage ('fixed' or 'object')

26

- case_sensitive: bool, case sensitive column name matching

27

- iter_row_buffer: int, rows to buffer during iteration

28

- write_bitcols: bool, write bit columns as FITS bit type

29

- ignore_empty: bool, ignore empty HDUs

30

- verbose: bool, print verbose information

31

- clobber: bool, overwrite existing file

32

"""

33

34

def close(self):

35

"""Close the FITS file and free resources."""

36

37

def write(self, data, extname=None, header=None, **kwargs):

38

"""

39

Write data to a new HDU.

40

41

Parameters:

42

- data: array-like, image or table data to write

43

- extname: str, extension name

44

- header: dict/list/FITSHDR, header keywords

45

- **kwargs: additional write options

46

"""

47

48

def write_image(self, img, extname=None, header=None, **kwargs):

49

"""Write image data to new image HDU."""

50

51

def write_table(self, data, extname=None, header=None, **kwargs):

52

"""Write table data to new table HDU."""

53

54

def create_image_hdu(self, **kwargs):

55

"""Create empty image HDU."""

56

57

def create_table_hdu(self, **kwargs):

58

"""Create empty table HDU."""

59

60

def reopen(self):

61

"""Reopen a closed FITS file."""

62

63

def movabs_ext(self, ext):

64

"""

65

Move to HDU by absolute extension number.

66

67

Parameters:

68

- ext: int, extension number (0-based)

69

"""

70

71

def movabs_hdu(self, hdunum):

72

"""

73

Move to HDU by HDU number.

74

75

Parameters:

76

- hdunum: int, HDU number (0-based)

77

"""

78

79

def movnam_ext(self, extname, hdutype=-1, extver=0):

80

"""

81

Move to HDU by extension name.

82

83

Parameters:

84

- extname: str, extension name

85

- hdutype: int, HDU type filter (default: ANY_HDU)

86

- extver: int, extension version

87

"""

88

89

def movnam_hdu(self, extname, hdutype=-1, extver=0):

90

"""

91

Move to HDU by name.

92

93

Parameters:

94

- extname: str, extension name

95

- hdutype: int, HDU type filter (default: ANY_HDU)

96

- extver: int, extension version

97

"""

98

99

def read_raw(self):

100

"""

101

Read raw FITS file data.

102

103

Returns:

104

bytes, raw file content

105

"""

106

107

def __getitem__(self, key):

108

"""

109

Access HDU by index or name.

110

111

Parameters:

112

- key: int/str/(str,int), HDU index, name, or (name, version)

113

114

Returns:

115

HDU object (ImageHDU, TableHDU, or AsciiTableHDU)

116

"""

117

118

def __contains__(self, key):

119

"""Check if HDU exists in file."""

120

121

def __len__(self):

122

"""Number of HDUs in file."""

123

124

def __iter__(self):

125

"""Iterate over all HDUs."""

126

127

def __enter__(self):

128

"""Context manager entry."""

129

130

def __exit__(self, exc_type, exc_val, exc_tb):

131

"""Context manager exit with automatic file closure."""

132

```

133

134

### Convenience Functions

135

136

High-level functions for common FITS operations without requiring explicit FITS object creation.

137

138

```python { .api }

139

def read(filename, ext=None, extver=None, columns=None, rows=None,

140

header=False, case_sensitive=False, upper=False, lower=False,

141

vstorage='fixed', verbose=False, trim_strings=False, **kwargs):

142

"""

143

Read data from FITS file.

144

145

Parameters:

146

- filename: str, path to FITS file

147

- ext: int/str, extension number or name (default: first with data)

148

- extver: int, extension version for duplicate names

149

- columns: list, column names to read (tables only)

150

- rows: list/array, specific rows to read (tables only)

151

- header: bool, return (data, header) tuple if True

152

- case_sensitive: bool, case sensitive column matching

153

- upper: bool, convert column names to uppercase

154

- lower: bool, convert column names to lowercase

155

- vstorage: str, variable length storage method

156

- verbose: bool, print verbose information

157

- trim_strings: bool, remove trailing whitespace

158

159

Returns:

160

numpy array (images) or structured array (tables), optionally with header

161

"""

162

163

def write(filename, data, extname=None, header=None, clobber=False,

164

compress=None, **kwargs):

165

"""

166

Write data to FITS file.

167

168

Parameters:

169

- filename: str, output file path

170

- data: array-like, data to write

171

- extname: str, extension name

172

- header: dict/list/FITSHDR, header keywords

173

- clobber: bool, overwrite existing file

174

- compress: str, compression type ('rice', 'gzip', 'plio', 'hcompress')

175

- **kwargs: additional write options

176

"""

177

178

def read_header(filename, ext=0, extver=None):

179

"""

180

Read FITS header without data.

181

182

Parameters:

183

- filename: str, path to FITS file

184

- ext: int/str, extension number or name

185

- extver: int, extension version

186

187

Returns:

188

FITSHDR object

189

"""

190

191

def read_scamp_head(filename, header=None):

192

"""

193

Read SCAMP .head file format.

194

195

Parameters:

196

- filename: str, path to .head file

197

- header: FITSHDR, existing header to update

198

199

Returns:

200

FITSHDR object

201

"""

202

```

203

204

## Usage Examples

205

206

### Basic File Operations

207

208

```python

209

import fitsio

210

211

# Open file for reading

212

with fitsio.FITS('data.fits') as fits:

213

print(f"File has {len(fits)} HDUs")

214

215

# Check what's in the file

216

for i, hdu in enumerate(fits):

217

print(f"HDU {i}: {hdu.get_exttype()}")

218

219

# Read data using convenience function

220

data = fitsio.read('data.fits', ext=1)

221

header = fitsio.read_header('data.fits', ext=1)

222

223

# Read with header

224

data, header = fitsio.read('data.fits', ext=1, header=True)

225

```

226

227

### Writing Files

228

229

```python

230

import numpy as np

231

import fitsio

232

233

# Create sample data

234

image = np.random.random((100, 100))

235

table_data = np.zeros(50, dtype=[('x', 'f8'), ('y', 'f8'), ('flux', 'f4')])

236

237

# Write using convenience function

238

fitsio.write('output.fits', image, clobber=True)

239

240

# Write with compression

241

fitsio.write('compressed.fits', image, compress='rice', clobber=True)

242

243

# Write multiple HDUs

244

with fitsio.FITS('multi.fits', 'rw', clobber=True) as fits:

245

fits.write(image, extname='IMAGE')

246

fits.write(table_data, extname='CATALOG')

247

```

248

249

### File Mode Operations

250

251

```python

252

# Open for read-write to modify existing file

253

with fitsio.FITS('data.fits', 'rw') as fits:

254

# Read existing data

255

old_data = fits[1].read()

256

257

# Append new rows to table

258

new_rows = np.zeros(10, dtype=old_data.dtype)

259

fits[1].append(new_rows)

260

261

# Write new HDU

262

fits.write(np.random.random((50, 50)), extname='NEW_IMAGE')

263

```

264

265

### HDU Access Patterns

266

267

```python

268

with fitsio.FITS('data.fits') as fits:

269

# Access by index

270

primary = fits[0]

271

table = fits[1]

272

273

# Access by name

274

if 'CATALOG' in fits:

275

catalog = fits['CATALOG']

276

277

# Access with version

278

if ('SCI', 2) in fits:

279

science = fits['SCI', 2]

280

281

# Iterate over all HDUs

282

for hdu in fits:

283

if hdu.has_data():

284

print(f"HDU has {hdu.get_exttype()} data")

285

```