fileio.py 1.7 KB

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