Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """ Remove given suffixes from all files in a directory (ignoring file
- extension).
- \b
- Dependencies:
- * click >= 7.0
- """
- import os
- import sys
- import shutil
- import ntpath
- import click
- @click.command(help=__doc__)
- @click.argument("suffixes_to_remove", nargs=-1, type=str)
- @click.option("--path-dir", type=str, show_default=True, default=".",
- help="Remove suffixes from all files in this directory.")
- @click.option("-s", "--existing-file-strategy", type=click.Choice([
- "error", "unique_name", "erase"
- ]), show_default=True, default="error",
- help="How to handle already existing files before renaming them. Choices "
- "are :\n"
- "* 'error': Raises an error and stop the script.\n"
- "* 'unique_name': Create a guaranted unique name for the new file "
- "by appending a number to it.\n"
- "* 'erase': Erase the already existing file.")
- @click.option("--quiet", is_flag=True,
- help="Set this flag if you want to completely silence all "
- "outputs to stdout.")
- def main(suffixes_to_remove, path_dir, existing_file_strategy, quiet):
- if quiet:
- sys.stdout = open(os.devnull, 'w')
- for file_name in os.listdir(path_dir):
- path_file = os.path.join(path_dir, file_name)
- if not os.path.isfile(path_file):
- continue
- file_basename = get_file_basename(file_name)
- for suffix in suffixes_to_remove:
- if file_basename.endswith(suffix):
- file_ext = get_file_extension(file_name)
- print(file_name, file_ext)
- file_ext = "." + file_ext if file_ext != "" else file_ext
- dest_file_name = "{}{}".format(
- remove_suffix(file_basename, suffix),
- file_ext
- )
- path_file_dest = os.path.join(path_dir, dest_file_name)
- rename_file(path_file, path_file_dest,
- strategy=existing_file_strategy)
- break
- def rename_file(path_file_src, path_file_dest, strategy):
- if os.path.exists(path_file_dest):
- if strategy == "error":
- raise OSError("Cannot rename \"{}\" into \"{}\", file already "
- "exists.".format(path_file_src, path_file_dest))
- exit(2)
- elif strategy == "unique_name":
- new_path_file_dest = generate_unique_filename(path_file_dest)
- print("Renaming \"{}\" into \"{}\"".format(path_file_src,
- new_path_file_dest))
- shutil.move(path_file_src, new_path_file_dest)
- elif strategy == "erase":
- print("Renaming \"{}\" into \"{}\" (erasing already existing "
- "file).".format(path_file_src, path_file_dest))
- shutil.move(path_file_src, path_file_dest)
- else:
- print("Renaming \"{}\" into \"{}\"".format(path_file_src,
- path_file_dest))
- shutil.move(path_file_src, path_file_dest)
- def generate_unique_filename(filepath):
- if os.path.isfile(filepath):
- dir_name = ntpath.dirname(filepath)
- dir_name = "." if dir_name == "" else dir_name
- base_name = get_file_basename(filepath)
- ext = get_file_extension(filepath)
- ext = "." + ext if ext != "" else ext
- suffix = 1
- new_filename = "{}_{}{}".format(
- base_name,
- str(suffix),
- ext
- )
- new_filepath = os.path.join(dir_name, new_filename)
- while os.path.isfile(new_filepath):
- suffix += 1
- new_filename = "{}_{}{}".format(
- "_".join(new_filename.split("_")[:-1]),
- str(suffix),
- ext
- )
- new_filepath = os.path.join(dir_name, new_filename)
- return new_filepath
- else:
- return filepath
- def remove_suffix(string, suffix):
- if len(suffix) == 0:
- return string
- return string[:-len(suffix)]
- def get_file_basename(file_name):
- file_name = ntpath.basename(file_name)
- assert len(file_name) > 0,\
- "Your file name must contains at least one character."
- if file_name[0] != "." and '.' in file_name:
- return ".".join(os.path.basename(file_name).split(".")[:-1])
- elif file_name[0] == "." and '.' in file_name[1:]:
- return ".".join(os.path.basename(file_name).split(".")[:-1])
- else:
- return file_name
- def get_file_extension(file_name):
- file_name = ntpath.basename(file_name)
- assert len(file_name) > 0,\
- "Your file name must contains at least one character."
- if file_name[0] != "." and '.' in file_name:
- return file_name.split(".")[-1]
- elif file_name[0] == "." and '.' in file_name[1:]:
- return file_name.split(".")[-1]
- else:
- return ""
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement