Created
February 20, 2019 18:00
-
-
Save willfurnass/50828cc8de5f4ac734b96cc0913946a8 to your computer and use it in GitHub Desktop.
Python snippet to export data to a file in a particular format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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