Skip to content

Context Manager

MicPy supports the use of context managers to handle files more efficiently. Using a context manager ensures that the file is properly closed after operations, even if an error occurs.

To use a context manager with a binary file, you can open the file using the with statement.

from micpy.bin import open

with open("A001_Delta_Gamma.conc1") as f:
    field = f.read(-1)

In this example, the file A001_Delta_Gamma.conc1 is opened within the with block, and its contents are read into the field variable. Once execution leaves the with block, the file is automatically closed, removing the need to explicitly call a close method.

The above code is functionally equivalent to:

from micpy.bin import open

f = open("A001_Delta_Gamma.conc1")
field = f.read(-1)
f.close()

Using context managers is the recommended approach when working with MICRESS binary files, as it improves code safety, readability, and ensures proper resource cleanup.