fileio.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. This module provides convenience functions for saving and loading of odML files.
  3. """
  4. import os
  5. from .tools.odmlparser import ODMLReader, ODMLWriter
  6. def load(filename, backend="xml", show_warnings=True):
  7. """
  8. Load an odML document from file.
  9. :param filename: Path and filename from where the odML document
  10. is to be loaded and parsed.
  11. :param backend: File format of the file containing the odML document.
  12. The default format is XML.
  13. :param show_warnings: Toggle whether to print warnings to the command line.
  14. :return: The parsed odML document.
  15. """
  16. if not os.path.exists(filename):
  17. msg = "File \'%s\' was not found!" % \
  18. (filename if len(filename) < 20 else "...%s" % filename[19:])
  19. raise FileNotFoundError(msg)
  20. reader = ODMLReader(backend, show_warnings)
  21. return reader.from_file(filename)
  22. def save(obj, filename, backend="xml"):
  23. """
  24. Save an open odML document to file of a specified format.
  25. :param obj: odML document do be saved.
  26. :param filename: Filename and path where the odML document
  27. should be saved.
  28. :param backend: Format in which the odML document is to be saved.
  29. The default format is XML.
  30. """
  31. writer = ODMLWriter(backend)
  32. if "." not in filename.split(os.pathsep)[-1]:
  33. filename = filename + ".%s" % backend
  34. return writer.write_file(obj, filename)
  35. def display(obj, backend="xml"):
  36. """
  37. Print an open odML document to the command line, formatted in the
  38. specified format.
  39. :param obj: odML document to be displayed.
  40. :param backend: Format in which the odML document is to be displayed.
  41. The default format is XML.
  42. """
  43. writer = ODMLWriter(backend)
  44. print(writer.to_string(obj))