/python/libopenimu/tools/FileManager.py

https://github.com/introlab/OpenIMU
Python | 82 lines | 61 code | 17 blank | 4 comment | 15 complexity | 62b011f00d2490ed2d894a3f799c803e MD5 | raw file
  1. import glob
  2. import os
  3. class FileManager:
  4. @staticmethod
  5. def get_file_list(from_path: str) -> dict:
  6. # Build file list
  7. file_list = {} # Dictionary: file and base_data_folder (data participant ID)
  8. # Add files to list
  9. files = glob.glob(from_path + "/**/*.*", recursive=True) # Files in sub folders
  10. for file in files:
  11. file_name = file.replace("/", os.sep)
  12. data_name = file.replace(from_path, "")
  13. data_name = data_name.replace("/", os.sep)
  14. # data_name = os.path.split(data_name)[0].replace(os.sep, "")
  15. data_name = data_name.split(os.sep)
  16. index = 0
  17. if data_name[index] == '':
  18. index = 1
  19. data_name = data_name[index]
  20. if file_name not in file_list:
  21. file_list[file_name] = data_name
  22. return file_list
  23. @staticmethod
  24. def merge_folders(root_src_dir: str, root_dst_dir: str):
  25. import os
  26. import shutil
  27. for src_dir, dirs, files in os.walk(root_src_dir):
  28. dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
  29. if not os.path.exists(dst_dir):
  30. os.makedirs(dst_dir)
  31. for file_ in files:
  32. src_file = os.path.join(src_dir, file_)
  33. dst_file = os.path.join(dst_dir, file_)
  34. if os.path.exists(dst_file):
  35. # in case of the src and dst are the same file
  36. if os.path.samefile(src_file, dst_file):
  37. continue
  38. os.remove(dst_file)
  39. shutil.move(src_file, dst_dir)
  40. @staticmethod
  41. def format_file_size(file_size: int, no_suffix: bool = False, ref_size: int = 0) -> str:
  42. kb_size = 1024
  43. mb_size = 1024 * kb_size
  44. gb_size = 1024 * mb_size
  45. tb_size = 1024 * gb_size
  46. if ref_size == 0:
  47. ref_size = file_size
  48. if ref_size <= kb_size:
  49. suffix = ' B'
  50. str_size = str(file_size)
  51. elif ref_size <= mb_size:
  52. suffix = ' KB'
  53. str_size = "{:.2f}".format(file_size / kb_size)
  54. elif ref_size <= gb_size:
  55. suffix = ' MB'
  56. str_size = "{:.2f}".format(file_size / mb_size)
  57. elif ref_size <= tb_size:
  58. suffix = ' GB'
  59. str_size = "{:.2f}".format(file_size / gb_size)
  60. else:
  61. suffix = ' TB'
  62. str_size = "{:.2f}".format(file_size / tb_size)
  63. if no_suffix:
  64. suffix = ''
  65. return str_size + suffix