compat.py 780 B

12345678910111213141516171819202122232425262728293031323334
  1. """Python 2/3 compatibility"""
  2. import json
  3. import sys
  4. # Handle reading and writing JSON in UTF-8, on Python 3 and 2.
  5. if sys.version_info[0] >= 3:
  6. # Python 3
  7. def write_json(obj, path, **kwargs):
  8. with open(path, 'w', encoding='utf-8') as f:
  9. json.dump(obj, f, **kwargs)
  10. def read_json(path):
  11. with open(path, 'r', encoding='utf-8') as f:
  12. return json.load(f)
  13. else:
  14. # Python 2
  15. def write_json(obj, path, **kwargs):
  16. with open(path, 'wb') as f:
  17. json.dump(obj, f, encoding='utf-8', **kwargs)
  18. def read_json(path):
  19. with open(path, 'rb') as f:
  20. return json.load(f)
  21. # FileNotFoundError
  22. try:
  23. FileNotFoundError = FileNotFoundError
  24. except NameError:
  25. FileNotFoundError = IOError