Skip to content
This repository has been archived by the owner on Nov 13, 2024. It is now read-only.

Commit

Permalink
Load also txt files into datalogger viewer and show a message, if loa…
Browse files Browse the repository at this point in the history
…d fails.
  • Loading branch information
BenediktBurger committed Oct 1, 2024
1 parent 3d19562 commit 819d520
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
26 changes: 25 additions & 1 deletion pyleco_extras/gui/data_logger/data/load_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,24 @@
import pickle
from typing import Any

import numpy as np


def load_datalogger_file(path: str | Path,
printing: bool = False,
) -> tuple[str,
dict[str, list[float]],
dict[str, Any]]:
"""Load a file saved with the data logger.
Can load files pickled, numpy text file, or JSON formatted.
:return: Header string, data dict, parameters dict
"""
if isinstance(path, str):
path = Path(path)
full_path = path
extensions = [".json", ".pkl"]
extensions = [".json", ".pkl", ".txt"]
while not full_path.is_file():
try:
full_path = Path(f"{path}{extensions.pop()}")
Expand All @@ -23,6 +31,22 @@ def load_datalogger_file(path: str | Path,
header, data, *more = json.load(full_path.open("r"))
elif suffix.lower() == ".pkl":
header, data, *more = pickle.load(full_path.open("rb"))
elif suffix.lower() == ".txt":
with full_path.open("r") as file:
lines = []
while True:
line = file.readline()
if line.startswith("# "):
lines.append(line[2:])
else:
break
header = "\n".join(lines)
variables = lines[-1].split() if lines else []
data_table = np.loadtxt(full_path)
data = {}
for i, var in enumerate(variables):
data[var] = list(data_table[:, i])
more = None
else:
raise ValueError(f"Invalid file name suffix '{suffix}'.")
metas = more[0] if more else {}
Expand Down
9 changes: 8 additions & 1 deletion pyleco_extras/gui/data_logger/data_logger_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,14 @@ def start(self):
return # user pressed cancel
self.last_path = file_name
path = Path(file_name)
header, data, meta = load_datalogger_file(path)
try:
header, data, meta = load_datalogger_file(path)
except Exception as exc:
msg = QtWidgets.QMessageBox()
msg.setWindowTitle("Loading file failed.")
msg.setText(f"Loading the file failed with {type(exc).__name__}:\n{exc}")
msg.exec()
return
self._lists = self.sanitize_data(data)
self.leHeader.setPlainText(header.rsplit("\n", maxsplit=1)[0])
self.set_configuration(meta.get("configuration", {}))
Expand Down

0 comments on commit 819d520

Please sign in to comment.