[Python] My .flush() is reducing a 28-character string to a 27-character string

Discussão em 'Python' iniciado por Stack, Junho 5, 2025.

  1. Stack

    Stack Membro Participativo

    For context, I'm working with .hdf files, which are used to model floods in HEC-RAS.

    The code I'm working with is this:

    def patch_mannings_n(class_hdf_path, material_ids, new_values, material_names):
    """
    Patch Manning's n values and print final Variables dataset.
    """
    from pathlib import Path

    with h5py.File(str(class_hdf_path), "r+") as f_cls:
    ids = list(f_cls["Raster Map"]["ID"][:])
    vars_ds = f_cls["Variables"][:]

    for matID, new_n, matName in zip(material_ids, new_values, material_names):

    decoded_name = vars_ds["Name"][idx].decode("ascii").rstrip("\x00")
    print(f"'{decoded_name}' → chars: {len(decoded_name)}, bytes: {len(decoded_name.encode('utf-8'))}")

    vars_ds["ManningsN"][idx] = np.float32(new_n)

    f_cls["Variables"][:] = vars_ds
    for idx, row in enumerate(vars_ds):
    name = row["Name"].decode("ascii").rstrip("\x00")
    name_len = len(name)
    n_val = float(row["ManningsN"])
    print(f"[{idx}] '{name}' (length {name_len}): n = {n_val:.4f}")
    f_cls.flush()

    with h5py.File(str(class_hdf_path), "r") as f:
    vars_ds = f["Variables"][:]
    print("\n Raw Name Bytes After Write:")
    for idx, row in enumerate(vars_ds):
    raw = row["Name"]
    decoded = raw.decode("ascii").rstrip("\x00")
    print(f"[{idx}] raw: {raw} | decoded: '{decoded}' | raw byte length: {len(raw)} | decoded length: {len(decoded)}")



    My print statements are outputting:

    • 'Emergent Herbaceous Wetlands' → chars: 28, bytes: 28
    • [11] 'Emergent Herbaceous Wetlands' (length 28): n = 0.0736
    • [11] raw: b'Emergent Herbaceous Wetland' | decoded: 'Emergent Herbaceous Wetland' | raw byte length: 27 | decoded length: 27

    so I'm fairly certain that the "truncation" occurs in the .flush() line. However, I can't figure out why.

    The original .hdf file (which I'm trying to modify -- I can't edit the live version because my changes don't stick, so I have to make a copy -- I'm assuming it's a similar reason to pass by value/pass by reference is important) holds 'Emergent Herbaceous Wetlands', so I don't think its an issue with the file type itself (I checked, the name uses S28 ASCII encoding).

    Can anyone help me figure out the issue? Any ideas would be much appreciated.

    Continue reading...

Compartilhe esta Página