0
# File Input/Output
1
2
PyVista provides comprehensive file I/O capabilities supporting over 20 file formats commonly used in scientific computing, CAD, and 3D graphics, with seamless integration to external mesh processing libraries.
3
4
## Capabilities
5
6
### Universal File Reading
7
8
#### Main Read Function
9
10
Universal file reader with automatic format detection.
11
12
```python { .api }
13
def read(filename, force_ext=None, file_format=None, progress_bar=False, **kwargs):
14
"""
15
Read any supported file format into appropriate PyVista dataset.
16
17
Parameters:
18
filename (str): Path to file to read
19
force_ext (str): Force specific file extension for format detection
20
file_format (str): Explicitly specify file format
21
progress_bar (bool): Show progress bar for large files
22
**kwargs: Reader-specific parameters
23
24
Returns:
25
DataSet: Appropriate PyVista dataset (PolyData, UnstructuredGrid, etc.)
26
"""
27
28
def get_reader(filename):
29
"""
30
Get appropriate reader class for file format.
31
32
Parameters:
33
filename (str): Path to file
34
35
Returns:
36
BaseReader: Reader class instance
37
"""
38
```
39
40
### VTK Format Support
41
42
#### Native VTK Files
43
44
Read VTK's native file formats with full feature support.
45
46
```python { .api }
47
class VTKDataSetReader:
48
"""Reader for VTK legacy format files (.vtk)."""
49
50
def __init__(self, filename):
51
"""Initialize reader with filename."""
52
53
def read(self) -> 'DataSet':
54
"""Read file and return dataset."""
55
56
class XMLPolyDataReader:
57
"""Reader for VTK XML PolyData files (.vtp)."""
58
59
def __init__(self, filename):
60
"""Initialize reader with filename."""
61
62
def read(self) -> PolyData:
63
"""Read file and return PolyData."""
64
65
class XMLUnstructuredGridReader:
66
"""Reader for VTK XML UnstructuredGrid files (.vtu)."""
67
68
def __init__(self, filename):
69
"""Initialize reader with filename."""
70
71
def read(self) -> UnstructuredGrid:
72
"""Read file and return UnstructuredGrid."""
73
74
class XMLImageDataReader:
75
"""Reader for VTK XML ImageData files (.vti)."""
76
77
def __init__(self, filename):
78
"""Initialize reader with filename."""
79
80
def read(self) -> ImageData:
81
"""Read file and return ImageData."""
82
```
83
84
### Common 3D Formats
85
86
#### STL Files
87
88
Support for STL (STereoLithography) format widely used in 3D printing and CAD.
89
90
```python { .api }
91
class STLReader:
92
"""
93
Reader for STL files (.stl).
94
95
Supports both ASCII and binary STL formats.
96
"""
97
98
def __init__(self, filename):
99
"""Initialize STL reader."""
100
101
def read(self) -> PolyData:
102
"""Read STL file and return PolyData mesh."""
103
```
104
105
#### PLY Files
106
107
Support for PLY (Stanford Triangle Format) files.
108
109
```python { .api }
110
class PLYReader:
111
"""
112
Reader for PLY files (.ply).
113
114
Supports both ASCII and binary PLY formats with custom properties.
115
"""
116
117
def __init__(self, filename):
118
"""Initialize PLY reader."""
119
120
def read(self) -> PolyData:
121
"""Read PLY file and return PolyData mesh."""
122
```
123
124
#### OBJ Files
125
126
Support for Wavefront OBJ format.
127
128
```python { .api }
129
class OBJReader:
130
"""
131
Reader for Wavefront OBJ files (.obj).
132
133
Supports geometry, materials, and texture coordinates.
134
"""
135
136
def __init__(self, filename):
137
"""Initialize OBJ reader."""
138
139
def read(self) -> PolyData:
140
"""Read OBJ file and return PolyData mesh."""
141
```
142
143
### Scientific and Engineering Formats
144
145
#### Exodus II Files
146
147
Support for Exodus II format used in finite element analysis.
148
149
```python { .api }
150
class ExodusIIReader:
151
"""
152
Reader for Exodus II files (.e, .exo, .g).
153
154
Supports finite element meshes with time-varying data.
155
"""
156
157
def __init__(self, filename):
158
"""Initialize Exodus reader."""
159
160
def read(self) -> MultiBlock:
161
"""Read Exodus file and return MultiBlock dataset."""
162
163
def set_object_status(self, object_type, object_id, status):
164
"""
165
Set status for reading specific objects.
166
167
Parameters:
168
object_type (str): Type of object ('ELEM_BLOCK', 'NODE_SET', etc.)
169
object_id (int): Object ID
170
status (bool): Whether to read object
171
"""
172
173
def get_times(self) -> list:
174
"""Get available time steps."""
175
176
def set_active_time_point(self, time_point):
177
"""
178
Set active time step.
179
180
Parameters:
181
time_point (int): Time step index
182
"""
183
184
def read_exodus(filename, **kwargs) -> MultiBlock:
185
"""
186
Convenience function to read Exodus files.
187
188
Parameters:
189
filename (str): Path to Exodus file
190
**kwargs: Reader options
191
192
Returns:
193
MultiBlock: Exodus dataset
194
"""
195
```
196
197
#### OpenFOAM Files
198
199
Support for OpenFOAM computational fluid dynamics format.
200
201
```python { .api }
202
class OpenFOAMReader:
203
"""
204
Reader for OpenFOAM case files.
205
206
Reads OpenFOAM simulation results including mesh and field data.
207
"""
208
209
def __init__(self, filename):
210
"""Initialize OpenFOAM reader."""
211
212
def read(self) -> MultiBlock:
213
"""Read OpenFOAM case and return MultiBlock dataset."""
214
215
def set_time_value(self, time_value):
216
"""
217
Set time step to read.
218
219
Parameters:
220
time_value (float): Time value
221
"""
222
```
223
224
### Image and Volume Formats
225
226
#### DICOM Medical Images
227
228
Support for medical imaging DICOM format.
229
230
```python { .api }
231
class DICOMReader:
232
"""
233
Reader for DICOM medical image files.
234
235
Supports single files and DICOM series.
236
"""
237
238
def __init__(self, filename):
239
"""Initialize DICOM reader."""
240
241
def read(self) -> ImageData:
242
"""Read DICOM data and return ImageData volume."""
243
```
244
245
#### Common Image Formats
246
247
Support for standard image formats as textures or height maps.
248
249
```python { .api }
250
class PNGReader:
251
"""Reader for PNG image files."""
252
253
def read(self) -> ImageData:
254
"""Read PNG as ImageData."""
255
256
class JPEGReader:
257
"""Reader for JPEG image files."""
258
259
def read(self) -> ImageData:
260
"""Read JPEG as ImageData."""
261
262
class TIFFReader:
263
"""Reader for TIFF image files."""
264
265
def read(self) -> ImageData:
266
"""Read TIFF as ImageData."""
267
268
def read_texture(filename) -> ImageData:
269
"""
270
Read image file as texture data.
271
272
Parameters:
273
filename (str): Path to image file
274
275
Returns:
276
ImageData: Image as volume data
277
"""
278
```
279
280
### MeshIO Integration
281
282
#### External Library Integration
283
284
Integration with MeshIO library for additional format support.
285
286
```python { .api }
287
def read_meshio(filename, **kwargs):
288
"""
289
Read file using MeshIO library.
290
291
Supports additional formats not natively supported by VTK.
292
293
Parameters:
294
filename (str): Path to file
295
**kwargs: MeshIO reader options
296
297
Returns:
298
DataSet: Converted PyVista dataset
299
"""
300
301
def from_meshio(mesh):
302
"""
303
Convert MeshIO mesh to PyVista dataset.
304
305
Parameters:
306
mesh (meshio.Mesh): MeshIO mesh object
307
308
Returns:
309
DataSet: PyVista dataset
310
"""
311
312
def to_meshio(mesh):
313
"""
314
Convert PyVista dataset to MeshIO mesh.
315
316
Parameters:
317
mesh (DataSet): PyVista dataset
318
319
Returns:
320
meshio.Mesh: MeshIO mesh object
321
"""
322
323
def save_meshio(mesh, filename, **kwargs):
324
"""
325
Save PyVista dataset using MeshIO.
326
327
Parameters:
328
mesh (DataSet): PyVista dataset to save
329
filename (str): Output filename
330
**kwargs: MeshIO writer options
331
"""
332
```
333
334
### File Writing
335
336
#### Universal Save Methods
337
338
Save datasets in appropriate formats.
339
340
```python { .api }
341
def save(self, filename, binary=True, texture=None):
342
"""
343
Save dataset to file with automatic format detection.
344
345
Parameters:
346
filename (str): Output filename with extension
347
binary (bool): Use binary format when available
348
texture (Texture): Optional texture to save with mesh
349
"""
350
```
351
352
#### Format-Specific Writers
353
354
Specialized writers for different formats.
355
356
```python { .api }
357
def save_vtk(mesh, filename, binary=True):
358
"""
359
Save as VTK legacy format (.vtk).
360
361
Parameters:
362
mesh (DataSet): Dataset to save
363
filename (str): Output filename
364
binary (bool): Use binary format
365
"""
366
367
def save_stl(mesh, filename, binary=True):
368
"""
369
Save as STL format (.stl).
370
371
Parameters:
372
mesh (PolyData): PolyData mesh to save
373
filename (str): Output filename
374
binary (bool): Use binary STL format
375
"""
376
377
def save_ply(mesh, filename, binary=True, texture_coordinates=None):
378
"""
379
Save as PLY format (.ply).
380
381
Parameters:
382
mesh (PolyData): PolyData mesh to save
383
filename (str): Output filename
384
binary (bool): Use binary PLY format
385
texture_coordinates (array): UV texture coordinates
386
"""
387
```
388
389
### Serialization
390
391
#### Pickle Support
392
393
Native Python serialization support.
394
395
```python { .api }
396
def save_pickle(mesh, filename):
397
"""
398
Save dataset using Python pickle.
399
400
Parameters:
401
mesh (DataSet): Dataset to pickle
402
filename (str): Output filename
403
"""
404
405
def read_pickle(filename):
406
"""
407
Read pickled dataset.
408
409
Parameters:
410
filename (str): Pickle file to read
411
412
Returns:
413
DataSet: Unpickled dataset
414
"""
415
416
def set_pickle_format(file_format):
417
"""
418
Set default pickle format for datasets.
419
420
Parameters:
421
file_format (str): Format ('vtk', 'xml', 'legacy')
422
"""
423
```
424
425
### Advanced File Operations
426
427
#### Multi-file and Time Series
428
429
Handle complex file organizations.
430
431
```python { .api }
432
class PVDReader:
433
"""
434
Reader for ParaView Data files (.pvd).
435
436
Handles time series and multi-file datasets.
437
"""
438
439
def __init__(self, filename):
440
"""Initialize PVD reader."""
441
442
def read(self) -> MultiBlock:
443
"""Read PVD file series."""
444
445
def get_time_values(self) -> list:
446
"""Get available time values."""
447
448
def set_active_time_value(self, time_value):
449
"""Set active time step."""
450
451
class TimeReader:
452
"""
453
Generic time series reader wrapper.
454
455
Provides unified interface for time-varying datasets.
456
"""
457
458
def __init__(self, reader):
459
"""Initialize with base reader."""
460
461
def update_time_step(self, time_step):
462
"""Update to specific time step."""
463
464
def get_time_range(self) -> tuple:
465
"""Get time range (min, max)."""
466
```
467
468
#### Compression and Optimization
469
470
Options for file size optimization.
471
472
```python { .api }
473
def set_vtkwriter_mode(mode):
474
"""
475
Set VTK writer compression mode.
476
477
Parameters:
478
mode (int): Compression level (0=off, 1=on, 2=appended)
479
"""
480
```
481
482
## Usage Examples
483
484
### Basic file I/O
485
486
```python
487
import pyvista as pv
488
489
# Read various file formats
490
mesh_vtk = pv.read('data.vtk') # VTK format
491
mesh_stl = pv.read('model.stl') # STL format
492
mesh_ply = pv.read('scan.ply') # PLY format
493
mesh_obj = pv.read('object.obj') # OBJ format
494
495
# Automatic format detection
496
mesh = pv.read('unknown_format.mesh')
497
498
# Save in different formats
499
mesh.save('output.vtk') # VTK legacy
500
mesh.save('output.vtp') # VTK XML PolyData
501
mesh.save('output.stl') # STL
502
mesh.save('output.ply') # PLY
503
```
504
505
### Working with scientific data
506
507
```python
508
import pyvista as pv
509
510
# Read Exodus finite element data
511
exodus_data = pv.read_exodus('simulation.e')
512
print(f"Time steps: {exodus_data.get_time_values()}")
513
514
# Read specific time step
515
reader = pv.ExodusIIReader('simulation.e')
516
reader.set_active_time_point(10)
517
data = reader.read()
518
519
# Read OpenFOAM case
520
foam_data = pv.read('case.foam')
521
522
# Read medical DICOM images
523
dicom_volume = pv.read('brain_scan.dcm')
524
```
525
526
### MeshIO integration
527
528
```python
529
import pyvista as pv
530
import meshio
531
532
# Read format not natively supported by VTK
533
mesh_gmsh = pv.read_meshio('model.msh') # Gmsh format
534
535
# Convert between PyVista and MeshIO
536
pv_mesh = pv.Sphere()
537
meshio_mesh = pv.to_meshio(pv_mesh)
538
539
# Save using MeshIO for additional formats
540
pv.save_meshio(pv_mesh, 'output.off') # OFF format
541
pv.save_meshio(pv_mesh, 'output.mesh') # Medit format
542
```
543
544
### Time series data
545
546
```python
547
import pyvista as pv
548
549
# Read time series data
550
reader = pv.PVDReader('time_series.pvd')
551
time_values = reader.get_time_values()
552
553
# Process each time step
554
results = []
555
for time_val in time_values:
556
reader.set_active_time_value(time_val)
557
data = reader.read()
558
# Process data for this time step
559
results.append(data.compute_derivative())
560
561
# Create animation from time series
562
plotter = pv.Plotter()
563
plotter.open_gif('animation.gif')
564
565
for result in results:
566
plotter.clear()
567
plotter.add_mesh(result, scalars='derivative')
568
plotter.write_frame()
569
570
plotter.close()
571
```