0
# File Operations
1
2
Core functionality for reading and writing DICOM files with comprehensive support for various transfer syntaxes, partial reading, metadata extraction, and flexible I/O operations.
3
4
## Capabilities
5
6
### Reading DICOM Files
7
8
Primary function for reading DICOM files from various sources with extensive configuration options for performance optimization and selective data loading.
9
10
```python { .api }
11
def dcmread(
12
fp,
13
defer_size=None,
14
stop_before_pixels=False,
15
force=False,
16
specific_tags=None
17
):
18
"""
19
Read and parse a DICOM file.
20
21
Parameters:
22
- fp: str, PathLike, or file-like object - File path or file-like object to read
23
- defer_size: int, str, float, or None - Defer reading large elements above this size threshold
24
- stop_before_pixels: bool - Stop reading at Pixel Data element (faster when pixels not needed)
25
- force: bool - Read file even if no DICOM File Meta Information header present
26
- specific_tags: list of int/tuple - Only read specified tags (faster for large files)
27
28
Returns:
29
FileDataset object containing the DICOM data
30
"""
31
```
32
33
### Writing DICOM Files
34
35
Primary function for writing DICOM datasets to files with options for format preservation and compression.
36
37
```python { .api }
38
def dcmwrite(
39
filename,
40
dataset,
41
/,
42
*,
43
implicit_vr=None,
44
little_endian=None,
45
enforce_file_format=False,
46
force_encoding=False,
47
overwrite=True
48
):
49
"""
50
Write a DICOM dataset to file.
51
52
Parameters:
53
- filename: str, PathLike, or file-like object - Output file path or file-like object
54
- dataset: Dataset - The dataset to write (positional-only)
55
- implicit_vr: bool or None - Use implicit VR encoding (keyword-only)
56
- little_endian: bool or None - Use little endian byte order (keyword-only)
57
- enforce_file_format: bool - Enforce DICOM File Format requirements (keyword-only)
58
- force_encoding: bool - Force encoding even with encoding issues (keyword-only)
59
- overwrite: bool - Overwrite existing files (keyword-only)
60
61
Returns:
62
None
63
"""
64
```
65
66
### Partial File Reading
67
68
Read specific portions of DICOM files without loading the entire dataset, useful for large files or metadata-only operations.
69
70
```python { .api }
71
def read_file_meta_info(fp):
72
"""
73
Read only the DICOM File Meta Information.
74
75
Parameters:
76
- fp: str, PathLike, or file-like object - File to read from
77
78
Returns:
79
FileMetaDataset containing File Meta Information elements
80
"""
81
82
def read_partial(fileobj, specific_tags=None, stop_when=None):
83
"""
84
Read specific data elements from DICOM file without full parsing.
85
86
Parameters:
87
- fileobj: file-like object - File to read from
88
- specific_tags: list - Only read these specific tags
89
- stop_when: callable - Function that returns True when to stop reading
90
91
Returns:
92
Dataset containing only the requested elements
93
"""
94
```
95
96
### Low-Level File Reading
97
98
Advanced functions for custom DICOM file parsing and element-by-element processing.
99
100
```python { .api }
101
def data_element_generator(fp, is_implicit_VR, is_little_endian, stop_when=None):
102
"""
103
Generate DataElement instances from a DICOM file.
104
105
Parameters:
106
- fp: file-like object - File to read from
107
- is_implicit_VR: bool - Whether the transfer syntax uses implicit VR
108
- is_little_endian: bool - Whether the transfer syntax uses little endian byte order
109
- stop_when: callable - Function that returns True when to stop reading
110
111
Yields:
112
DataElement instances as they are read
113
"""
114
115
def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None):
116
"""
117
Read dataset from file-like object.
118
119
Parameters:
120
- fp: file-like object - File to read from
121
- is_implicit_VR: bool - Whether VR is implicit
122
- is_little_endian: bool - Byte order
123
- bytelength: int - Number of bytes to read (None for all)
124
125
Returns:
126
Dataset containing the read elements
127
"""
128
129
def read_sequence(fp, is_implicit_VR, is_little_endian, bytelength):
130
"""
131
Read a DICOM sequence from file.
132
133
Parameters:
134
- fp: file-like object - File to read from
135
- is_implicit_VR: bool - Whether VR is implicit
136
- is_little_endian: bool - Byte order
137
- bytelength: int - Number of bytes in sequence
138
139
Returns:
140
Sequence object containing datasets
141
"""
142
```
143
144
### Low-Level File Writing
145
146
Advanced functions for custom DICOM file creation and element-by-element writing.
147
148
```python { .api }
149
def write_dataset(fp, dataset, parent_encoding=None):
150
"""
151
Write dataset to a file-like object.
152
153
Parameters:
154
- fp: file-like object - File to write to
155
- dataset: Dataset - Dataset to write
156
- parent_encoding: tuple - Parent dataset's (VR, endianness) info
157
158
Returns:
159
None
160
"""
161
162
def write_data_element(fp, data_element, encodings=None):
163
"""
164
Write a single DataElement to file.
165
166
Parameters:
167
- fp: file-like object - File to write to
168
- data_element: DataElement - Element to write
169
- encodings: tuple - (is_implicit_VR, is_little_endian)
170
171
Returns:
172
None
173
"""
174
```
175
176
### VR Correction and Validation
177
178
Functions for handling ambiguous Value Representations and ensuring proper DICOM formatting.
179
180
```python { .api }
181
def correct_ambiguous_vr(data_element, dataset):
182
"""
183
Correct ambiguous VR based on context.
184
185
Parameters:
186
- data_element: DataElement - Element with potentially ambiguous VR
187
- dataset: Dataset - Context dataset for VR determination
188
189
Returns:
190
DataElement with corrected VR
191
"""
192
193
def correct_ambiguous_vr_element(data_element, dataset, is_little_endian):
194
"""
195
Correct element VR when transfer syntax context is known.
196
197
Parameters:
198
- data_element: DataElement - Element to correct
199
- dataset: Dataset - Context dataset
200
- is_little_endian: bool - Transfer syntax byte order
201
202
Returns:
203
DataElement with corrected VR
204
"""
205
```
206
207
### Format-Specific Writers
208
209
Specialized writing functions for specific DICOM Value Representations.
210
211
```python { .api }
212
def write_numbers(fp, data_element, struct_format):
213
"""
214
Write numeric data elements.
215
216
Parameters:
217
- fp: file-like object - File to write to
218
- data_element: DataElement - Numeric element to write
219
- struct_format: str - Struct format string for packing
220
221
Returns:
222
None
223
"""
224
225
def write_string(fp, data_element, encoding):
226
"""
227
Write string data elements with proper encoding.
228
229
Parameters:
230
- fp: file-like object - File to write to
231
- data_element: DataElement - String element to write
232
- encoding: str - Character encoding to use
233
234
Returns:
235
None
236
"""
237
238
def write_text(fp, data_element, encoding):
239
"""
240
Write text data elements (UT VR).
241
242
Parameters:
243
- fp: file-like object - File to write to
244
- data_element: DataElement - Text element to write
245
- encoding: str - Character encoding to use
246
247
Returns:
248
None
249
"""
250
251
def write_PN(fp, data_element, encoding):
252
"""
253
Write Person Name data elements.
254
255
Parameters:
256
- fp: file-like object - File to write to
257
- data_element: DataElement - Person Name element to write
258
- encoding: str - Character encoding to use
259
260
Returns:
261
None
262
"""
263
264
def write_DA(fp, data_element):
265
"""
266
Write Date (DA) data elements.
267
268
Parameters:
269
- fp: file-like object - File to write to
270
- data_element: DataElement - Date element to write
271
272
Returns:
273
None
274
"""
275
276
def write_TM(fp, data_element):
277
"""
278
Write Time (TM) data elements.
279
280
Parameters:
281
- fp: file-like object - File to write to
282
- data_element: DataElement - Time element to write
283
284
Returns:
285
None
286
"""
287
288
def write_DT(fp, data_element):
289
"""
290
Write DateTime (DT) data elements.
291
292
Parameters:
293
- fp: file-like object - File to write to
294
- data_element: DataElement - DateTime element to write
295
296
Returns:
297
None
298
"""
299
```
300
301
## Usage Examples
302
303
### Basic File Reading
304
305
```python
306
from pydicom import dcmread
307
308
# Read complete DICOM file
309
dataset = dcmread("image.dcm")
310
311
# Read without pixel data for faster metadata access
312
header_only = dcmread("image.dcm", stop_before_pixels=True)
313
314
# Read only specific tags
315
patient_info = dcmread("image.dcm", specific_tags=[0x00100010, 0x00100020])
316
317
# Force reading non-standard files
318
questionable_file = dcmread("maybe_dicom.bin", force=True)
319
```
320
321
### Metadata-Only Operations
322
323
```python
324
from pydicom.filereader import read_file_meta_info
325
326
# Read only File Meta Information
327
meta_info = read_file_meta_info("image.dcm")
328
print(f"Transfer Syntax: {meta_info.TransferSyntaxUID}")
329
print(f"Implementation Class: {meta_info.ImplementationClassUID}")
330
```
331
332
### Selective Element Reading
333
334
```python
335
from pydicom.filereader import read_partial
336
337
# Read only patient and study information
338
with open("large_image.dcm", "rb") as f:
339
patient_study = read_partial(f, specific_tags=[
340
0x00100010, # Patient Name
341
0x00100020, # Patient ID
342
0x0020000D, # Study Instance UID
343
0x00200010 # Study ID
344
])
345
```
346
347
### File Writing with Compression
348
349
```python
350
from pydicom import dcmread, dcmwrite
351
352
# Read original file
353
dataset = dcmread("original.dcm")
354
355
# Modify and save preserving original format
356
dataset.PatientName = "Anonymous"
357
dcmwrite("anonymized.dcm", dataset, write_like_original=True)
358
359
# Save with new format (will use Explicit VR Little Endian)
360
dcmwrite("converted.dcm", dataset, write_like_original=False)
361
```
362
363
### Low-Level Processing
364
365
```python
366
from pydicom.filereader import data_element_generator
367
368
# Process elements one by one without loading entire file
369
with open("huge_file.dcm", "rb") as f:
370
# Skip File Meta Information
371
f.seek(132) # Standard meta info size
372
373
for elem in data_element_generator(f, True, True): # Implicit VR, Little Endian
374
if elem.tag == 0x7FE00010: # Pixel Data
375
print(f"Found pixel data: {len(elem.value)} bytes")
376
break
377
print(f"{elem.keyword}: {elem.value}")
378
```