utils_fs.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import os
  2. import re
  3. import shutil
  4. def get_path_stem(path):
  5. """
  6. References:
  7. `std::filesystem::path::stem` since C++17
  8. """
  9. return os.path.splitext(os.path.basename(path))[0]
  10. def replace_path_stem(path, new_stem):
  11. dirname, basename = os.path.split(path)
  12. stem, extname = os.path.splitext(basename)
  13. if isinstance(new_stem, str):
  14. return os.path.join(dirname, new_stem + extname)
  15. elif hasattr(new_stem, '__call__'):
  16. return os.path.join(dirname, new_stem(stem) + extname)
  17. else:
  18. raise ValueError('Unsupported Type!')
  19. def get_path_extension(path):
  20. """
  21. References:
  22. `std::filesystem::path::extension` since C++17
  23. Notes:
  24. Not fully consistent with `std::filesystem::path::extension`
  25. """
  26. return os.path.splitext(os.path.basename(path))[1]
  27. def replace_path_extension(path, new_extname=None):
  28. """Replaces the extension with new_extname or removes it when the default value is used.
  29. Firstly, if this path has an extension, it is removed. Then, a dot character is appended
  30. to the pathname, if new_extname is not empty or does not begin with a dot character.
  31. References:
  32. `std::filesystem::path::replace_extension` since C++17
  33. """
  34. filename_wo_ext = os.path.splitext(path)[0]
  35. if new_extname == '' or new_extname is None:
  36. return filename_wo_ext
  37. elif new_extname.startswith('.'):
  38. return ''.join([filename_wo_ext, new_extname])
  39. else:
  40. return '.'.join([filename_wo_ext, new_extname])
  41. def makedirs(name, mode=0o755):
  42. """
  43. References:
  44. mmcv.mkdir_or_exist
  45. """
  46. if name == '':
  47. return
  48. name = os.path.expanduser(name)
  49. os.makedirs(name, mode=mode, exist_ok=True)
  50. def listdirs(paths, path_sep=None, full_path=True):
  51. """Enhancement on `os.listdir`
  52. """
  53. assert isinstance(paths, (str, tuple, list))
  54. if isinstance(paths, str):
  55. path_sep = path_sep or os.path.pathsep
  56. paths = paths.split(path_sep)
  57. all_filenames = []
  58. for path in paths:
  59. path_ex = os.path.expanduser(path)
  60. filenames = os.listdir(path_ex)
  61. if full_path:
  62. filenames = [os.path.join(path_ex, filename) for filename in filenames]
  63. all_filenames.extend(filenames)
  64. return all_filenames
  65. def get_all_filenames(path, extensions=None, is_valid_file=None):
  66. if (extensions is not None) and (is_valid_file is not None):
  67. raise ValueError("Both extensions and is_valid_file cannot "
  68. "be not None at the same time")
  69. if is_valid_file is None:
  70. if extensions is not None:
  71. def is_valid_file(filename):
  72. return filename.lower().endswith(extensions)
  73. else:
  74. def is_valid_file(filename):
  75. return True
  76. all_filenames = []
  77. path_ex = os.path.expanduser(path)
  78. for root, _, filenames in sorted(os.walk(path_ex, followlinks=True)):
  79. for filename in sorted(filenames):
  80. fullname = os.path.join(root, filename)
  81. if is_valid_file(fullname):
  82. all_filenames.append(fullname)
  83. return all_filenames
  84. def get_top_level_dirs(path, full_path=True):
  85. if path is None:
  86. path = os.getcwd()
  87. path_ex = os.path.expanduser(path)
  88. filenames = os.listdir(path_ex)
  89. if full_path:
  90. return [os.path.join(path_ex, item) for item in filenames
  91. if os.path.isdir(os.path.join(path_ex, item))]
  92. else:
  93. return [item for item in filenames
  94. if os.path.isdir(os.path.join(path_ex, item))]
  95. def replace_invalid_filename_char(filename, new_char='_'):
  96. assert isinstance(new_char, str)
  97. control_chars = ''.join((map(chr, range(0x00, 0x20))))
  98. pattern = r'[\\/*?:"<>|{}]'.format(control_chars)
  99. return re.sub(pattern, new_char, filename)
  100. def copy_file(src, dst_dir, action_if_exist=None):
  101. """
  102. Args:
  103. src: source file path
  104. dst_dir: dest dir
  105. action_if_exist:
  106. None: when dest file exists, no operation
  107. overwritten: when dest file exists, overwritten
  108. rename: when dest file exists, rename it
  109. Returns:
  110. dest file basename
  111. """
  112. src_basename = os.path.basename(src)
  113. dst_fullname = os.path.join(dst_dir, src_basename)
  114. if action_if_exist is None:
  115. if not os.path.exists(dst_fullname):
  116. makedirs(dst_dir)
  117. shutil.copy(src, dst_dir)
  118. elif action_if_exist.lower() == 'overwritten':
  119. makedirs(dst_dir)
  120. # shutil.copy
  121. # If dst is a directory, a file with the same basename as src is
  122. # created (or overwritten) in the directory specified.
  123. shutil.copy(src, dst_dir)
  124. elif action_if_exist.lower() == 'rename':
  125. src_stem, src_extname = os.path.splitext(src_basename)
  126. suffix = 2
  127. while os.path.exists(dst_fullname):
  128. dst_basename = '{} ({}){}'.format(src_stem, suffix, src_extname)
  129. dst_fullname = os.path.join(dst_dir, dst_basename)
  130. suffix += 1
  131. else:
  132. makedirs(dst_dir)
  133. shutil.copy(src, dst_fullname)
  134. else:
  135. raise ValueError('Invalid action_if_exist, got {}.'.format(action_if_exist))
  136. return os.path.basename(dst_fullname)
  137. def move_file(src, dst_dir, action_if_exist=None):
  138. """
  139. Args:
  140. src: source file path
  141. dst_dir: dest dir
  142. action_if_exist:
  143. None: when dest file exists, no operation
  144. overwritten: when dest file exists, overwritten
  145. rename: when dest file exists, rename it
  146. Returns:
  147. dest file basename
  148. """
  149. src_basename = os.path.basename(src)
  150. dst_fullname = os.path.join(dst_dir, src_basename)
  151. if action_if_exist is None:
  152. if not os.path.exists(dst_fullname):
  153. makedirs(dst_dir)
  154. shutil.move(src, dst_dir)
  155. elif action_if_exist.lower() == 'overwritten':
  156. if os.path.exists(dst_fullname):
  157. os.remove(dst_fullname)
  158. makedirs(dst_dir)
  159. # shutil.move
  160. # If the destination already exists but is not a directory,
  161. # it may be overwritten depending on os.rename() semantics.
  162. shutil.move(src, dst_dir)
  163. elif action_if_exist.lower() == 'rename':
  164. src_stem, src_extname = os.path.splitext(src_basename)
  165. suffix = 2
  166. while os.path.exists(dst_fullname):
  167. dst_basename = '{} ({}){}'.format(src_stem, suffix, src_extname)
  168. dst_fullname = os.path.join(dst_dir, dst_basename)
  169. suffix += 1
  170. else:
  171. makedirs(dst_dir)
  172. shutil.move(src, dst_fullname)
  173. else:
  174. raise ValueError('Invalid action_if_exist, got {}.'.format(action_if_exist))
  175. return os.path.basename(dst_fullname)