utils_file_io.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import json
  2. import numbers
  3. from collections import OrderedDict
  4. def load_list(filename, encoding='utf-8', start=0, stop=None):
  5. assert isinstance(start, numbers.Integral) and start >= 0
  6. assert (stop is None) or (isinstance(stop, numbers.Integral) and stop > start)
  7. lines = []
  8. with open(filename, 'r', encoding=encoding) as f:
  9. for _ in range(start):
  10. f.readline()
  11. for k, line in enumerate(f):
  12. if (stop is not None) and (k + start > stop):
  13. break
  14. lines.append(line.rstrip('\n'))
  15. return lines
  16. def save_list(filename, list_obj, encoding='utf-8', append_break=True):
  17. with open(filename, 'w', encoding=encoding) as f:
  18. if append_break:
  19. for item in list_obj:
  20. f.write(str(item) + '\n')
  21. else:
  22. for item in list_obj:
  23. f.write(str(item))
  24. def load_json(filename, encoding='utf-8'):
  25. with open(filename, 'r', encoding=encoding) as f:
  26. data = json.load(f, object_pairs_hook=OrderedDict)
  27. return data
  28. def save_json(filename, data, encoding='utf-8', sort_keys=False):
  29. if not filename.endswith('.json'):
  30. filename = filename + '.json'
  31. with open(filename, 'w', encoding=encoding) as f:
  32. json.dump(data, f, indent=4, separators=(',',': '),
  33. ensure_ascii=False, sort_keys=sort_keys)