Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python snippet to export data to a file in a particular format
import os
from typing import Dict
import numpy as np
def export_data(data: Dict[np.ndarray],
filename: str,
cols_per_line: int = 8) -> None:
"""Export dictionary of 1d float arrays to a file.
Output files are generated by
- Iterating over the key-value pairs of the dictionary
- Writing out the dictionary values (1d float arrays) so there are two
spaces between array elements unless:
- The column index + 1 is divisible by a constant (``cols_per_line``)
- or we've reached the end of the array
in which case we write a newline character.
"""
with open(filename, 'w') as output_file:
for key in data:
arr_size = data[key].size
for col_idx, val in enumerate(data[key]):
sep = os.linesep if (col_idx + 1) % cols_per_line == 0 or (col_idx + 1) == arr_size else ' '
print(f"{val:.6f}", end=sep, file=output_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment