SHARE
TWEET

Untitled

a guest Apr 24th, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """ Remove given suffixes from all files in a directory (ignoring file
  2. extension).
  3.  
  4. \b
  5. Dependencies:
  6. * click >= 7.0
  7. """
  8.  
  9. import os
  10. import sys
  11. import shutil
  12. import ntpath
  13.  
  14. import click
  15.  
  16.  
  17. @click.command(help=__doc__)
  18. @click.argument("suffixes_to_remove", nargs=-1, type=str)
  19. @click.option("--path-dir", type=str, show_default=True, default=".",
  20.               help="Remove suffixes from all files in this directory.")
  21. @click.option("-s", "--existing-file-strategy", type=click.Choice([
  22.     "error", "unique_name", "erase"
  23. ]), show_default=True, default="error",
  24.     help="How to handle already existing files before renaming them. Choices "
  25.          "are :\n"
  26.          "* 'error': Raises an error and stop the script.\n"
  27.          "* 'unique_name': Create a guaranted unique name for the new file "
  28.          "by appending a number to it.\n"
  29.          "* 'erase': Erase the already existing file.")
  30. @click.option("--quiet", is_flag=True,
  31.               help="Set this flag if you want to completely silence all "
  32.                    "outputs to stdout.")
  33. def main(suffixes_to_remove, path_dir, existing_file_strategy, quiet):
  34.     if quiet:
  35.         sys.stdout = open(os.devnull, 'w')
  36.  
  37.     for file_name in os.listdir(path_dir):
  38.         path_file = os.path.join(path_dir, file_name)
  39.         if not os.path.isfile(path_file):
  40.             continue
  41.  
  42.         file_basename = get_file_basename(file_name)
  43.         for suffix in suffixes_to_remove:
  44.             if file_basename.endswith(suffix):
  45.                 file_ext = get_file_extension(file_name)
  46.                 print(file_name, file_ext)
  47.                 file_ext = "." + file_ext if file_ext != "" else file_ext
  48.                 dest_file_name = "{}{}".format(
  49.                     remove_suffix(file_basename, suffix),
  50.                     file_ext
  51.                 )
  52.                 path_file_dest = os.path.join(path_dir, dest_file_name)
  53.                 rename_file(path_file, path_file_dest,
  54.                             strategy=existing_file_strategy)
  55.                 break
  56.  
  57.  
  58. def rename_file(path_file_src, path_file_dest, strategy):
  59.     if os.path.exists(path_file_dest):
  60.         if strategy == "error":
  61.             raise OSError("Cannot rename \"{}\" into \"{}\", file already "
  62.                           "exists.".format(path_file_src, path_file_dest))
  63.             exit(2)
  64.         elif strategy == "unique_name":
  65.             new_path_file_dest = generate_unique_filename(path_file_dest)
  66.             print("Renaming \"{}\" into \"{}\"".format(path_file_src,
  67.                                                        new_path_file_dest))
  68.             shutil.move(path_file_src, new_path_file_dest)
  69.         elif strategy == "erase":
  70.             print("Renaming \"{}\" into \"{}\" (erasing already existing "
  71.                   "file).".format(path_file_src, path_file_dest))
  72.             shutil.move(path_file_src, path_file_dest)
  73.     else:
  74.         print("Renaming \"{}\" into \"{}\"".format(path_file_src,
  75.                                                    path_file_dest))
  76.         shutil.move(path_file_src, path_file_dest)
  77.  
  78.  
  79. def generate_unique_filename(filepath):
  80.     if os.path.isfile(filepath):
  81.         dir_name = ntpath.dirname(filepath)
  82.         dir_name = "." if dir_name == "" else dir_name
  83.         base_name = get_file_basename(filepath)
  84.         ext = get_file_extension(filepath)
  85.         ext = "." + ext if ext != "" else ext
  86.  
  87.         suffix = 1
  88.         new_filename = "{}_{}{}".format(
  89.             base_name,
  90.             str(suffix),
  91.             ext
  92.         )
  93.         new_filepath = os.path.join(dir_name, new_filename)
  94.         while os.path.isfile(new_filepath):
  95.             suffix += 1
  96.             new_filename = "{}_{}{}".format(
  97.                 "_".join(new_filename.split("_")[:-1]),
  98.                 str(suffix),
  99.                 ext
  100.             )
  101.             new_filepath = os.path.join(dir_name, new_filename)
  102.         return new_filepath
  103.     else:
  104.         return filepath
  105.  
  106.  
  107. def remove_suffix(string, suffix):
  108.     if len(suffix) == 0:
  109.         return string
  110.     return string[:-len(suffix)]
  111.  
  112.  
  113. def get_file_basename(file_name):
  114.     file_name = ntpath.basename(file_name)
  115.     assert len(file_name) > 0,\
  116.         "Your file name must contains at least one character."
  117.  
  118.     if file_name[0] != "." and '.' in file_name:
  119.         return ".".join(os.path.basename(file_name).split(".")[:-1])
  120.     elif file_name[0] == "." and '.' in file_name[1:]:
  121.         return ".".join(os.path.basename(file_name).split(".")[:-1])
  122.     else:
  123.         return file_name
  124.  
  125.  
  126. def get_file_extension(file_name):
  127.     file_name = ntpath.basename(file_name)
  128.     assert len(file_name) > 0,\
  129.         "Your file name must contains at least one character."
  130.  
  131.     if file_name[0] != "." and '.' in file_name:
  132.         return file_name.split(".")[-1]
  133.     elif file_name[0] == "." and '.' in file_name[1:]:
  134.         return file_name.split(".")[-1]
  135.     else:
  136.         return ""
  137.  
  138.  
  139. if __name__ == '__main__':
  140.     main()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top