Writing to a file target

[1]:
# get input GRIB data
import os

import earthkit.data as ekd

ds = ekd.from_source("sample", "test.grib").to_fieldlist()

Using a file path

We use to_target() to write the GRIB fieldlist/field into a file. The encoder is automatically guessed from the input data. Alternatively, we can create a target object with create_target() and directly write to it.

[2]:
# calling to_target
ds.to_target("file", "_res_t_file_handler.grib")

# using write on the target object
with ekd.create_target("file", "_res_t_file_handler.grib") as t:
    t.write(ds)

Using a file-like object

A file-like object passed to the target is not closed, even when the target is closed or created with a context manager.

[3]:
fp = open("_res_t_file_handler.grib", "wb")
ds.to_target("file", fp)

# the file object is still open
print(fp.closed)

# we need to close it manually
fp.close()
False
[4]:
fp = open("_res_t_file_handler.grib", "wb")

# the context manager will call close() on the target
with ekd.create_target("file", fp) as t:
    t.write(ds)

# the file object is still open
print(fp.closed)

# we need to close it manually
fp.close()
False

The simplest solution to this problem is to use a context manager for the file-like object.

[5]:
with open("_res_t_file_handler.grib", "wb") as fp:
    ds.to_target("file", fp)

Appending to a file

When using a file path we can use the append=True option to append to the output.

[6]:
# calling to_target
out_file = "_res_t1_file_handler.grib"
if os.path.isfile(out_file):
    os.remove(out_file)

ds[0].to_target("file", out_file, append=True)
len(ekd.from_source("file", out_file).to_fieldlist())
[6]:
1
[7]:
ds[1].to_target("file", out_file, append=True)
len(ekd.from_source("file", out_file).to_fieldlist())
[7]:
2
[ ]: