utils_file_io.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import json
  2. import base64
  3. import numbers
  4. import warnings
  5. from collections import OrderedDict
  6. def load_list(filename, encoding='utf-8', start=0, stop=None):
  7. assert isinstance(start, numbers.Integral) and start >= 0
  8. assert (stop is None) or (isinstance(stop, numbers.Integral) and stop > start)
  9. lines = []
  10. with open(filename, 'r', encoding=encoding) as f:
  11. for _ in range(start):
  12. f.readline()
  13. for k, line in enumerate(f):
  14. if (stop is not None) and (k + start > stop):
  15. break
  16. lines.append(line.rstrip('\n'))
  17. return lines
  18. def save_list(filename, list_obj, encoding='utf-8', append_break=True):
  19. with open(filename, 'w', encoding=encoding) as f:
  20. if append_break:
  21. for item in list_obj:
  22. f.write(str(item) + '\n')
  23. else:
  24. for item in list_obj:
  25. f.write(str(item))
  26. def load_json(filename, encoding='utf-8'):
  27. with open(filename, 'r', encoding=encoding) as f:
  28. data = json.load(f, object_pairs_hook=OrderedDict)
  29. return data
  30. def save_json(filename, data, encoding='utf-8', indent=4, cls=None, sort_keys=False):
  31. if not filename.endswith('.json'):
  32. filename = filename + '.json'
  33. with open(filename, 'w', encoding=encoding) as f:
  34. json.dump(data, f, indent=indent, separators=(',',': '),
  35. ensure_ascii=False, cls=cls, sort_keys=sort_keys)
  36. def load_bytes(filename: str, use_base64: bool = False) -> bytes:
  37. """Open the file in bytes mode, read it, and close the file.
  38. References:
  39. pathlib.Path.read_bytes
  40. """
  41. with open(filename, 'rb') as f:
  42. data = f.read()
  43. if use_base64:
  44. data = base64.b64encode(data)
  45. return data
  46. def save_bytes(filename: str, data: bytes, use_base64: bool = False) -> int:
  47. """Open the file in bytes mode, write to it, and close the file.
  48. References:
  49. pathlib.Path.write_bytes
  50. """
  51. if use_base64:
  52. data = base64.b64decode(data)
  53. with open(filename, 'wb') as f:
  54. ret = f.write(data)
  55. return ret
  56. def load_as_base64(filename: str) -> bytes:
  57. warnings.warn('khandy.load_as_base64 will be deprecated, use khandy.load_bytes instead!')
  58. return load_bytes(filename, True)