Advertisement
Guest User

script to remove Windows invalid characters from filename

a guest
Nov 5th, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.52 KB | None | 0 0
  1. import re, argparse, sys, os
  2. from colorama import just_fix_windows_console
  3. from termcolor import cprint
  4. from termcolor._types import Color
  5.  
  6. # thanks https://github.com/strohel/works/blob/
  7. # 4abb93baab1d89e2275af6ec04e0b2e4351a7e76/dipl-DVD-ROM/Ceygen/support/visualize_stats.py#L#18
  8.  
  9. tempfile = "temp__batch_remove_invalid.txt"
  10.  
  11. # ----- ----- ----- ----- ----- -----
  12. #         Arguments Handling
  13. # ----- ----- ----- ----- ----- -----
  14.  
  15.  
  16. just_fix_windows_console()
  17. parser = argparse.ArgumentParser(
  18.     formatter_class=argparse.RawTextHelpFormatter,
  19.     description="""
  20.    description:
  21.      Transforms strings into valid filenames for Windows' Batch.
  22.  
  23.      Accepts inputs:
  24.      -------
  25.      list[str]
  26.          any form
  27.  
  28.      Returns
  29.      -------
  30.      list[str]
  31.          string, valid batch filename
  32.    """, usage="")
  33.  
  34. parser.add_argument("-d", "-dbg", "--debug",
  35.                     action="store_true",
  36.                     help="Show debug log.")
  37.  
  38. parser.add_argument("-f",
  39.                     dest="file",
  40.                     help="Consume inputs from given file.")
  41.  
  42. parser.add_argument("--file",
  43.                     dest="file",
  44.                     help=argparse.SUPPRESS)
  45.  
  46. parser.add_argument("input",
  47.                     nargs=argparse.REMAINDER,  # allows accepting hyphens
  48.                     help="Input, in supported form.")
  49.  
  50. #  custom Usage
  51. nl = "\n"
  52. all_inputs = " ".join(["[-" + action.option_strings[0][-1:] + "]"
  53.                        for action in parser._actions[:-1]])
  54. last_input = parser._actions
  55. parser.usage = f'\
  56.    {nl}  \
  57.    {parser.prog} \
  58.    {all_inputs} \
  59.    {last_input[-1].dest.upper()}'
  60.  
  61. #  flags handling
  62. parsed = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
  63. whether_debug = parsed.debug
  64. whether_from_file = parsed.file
  65.  
  66. if whether_from_file is not None:
  67.     user_list = []
  68.     with open(whether_from_file, "r") as file:
  69.         for line in file:
  70.             user_list.append(line.strip())
  71. else:
  72.     user_list = parsed.input
  73.  
  74.  
  75. # ----- ----- ----- ----- ----- -----
  76. #               Helpers
  77. # ----- ----- ----- ----- ----- -----
  78.  
  79.  
  80. def d(
  81.     str:   None |   str = None,
  82.     level: None |   str = None,
  83.     color: None | Color = None
  84. ) -> None:
  85.     '''Print debug message.'''
  86.     if color is None:
  87.         color = "yellow"
  88.     if level is None:
  89.         level = "debug"
  90.  
  91.     if whether_debug is True and level == "debug":
  92.         cprint(f'[DEBUG] {str}', "yellow")
  93.     if level == "none":
  94.         cprint(f'{str}', color)
  95.  
  96.  
  97. def validate(text: str):
  98.     '''Transforms strings into valid filenames for Windows' Batch.
  99.       Valid chars: %!@#$%'¨&()_+-=.,;
  100.    '''
  101.     invalids = ["\\", "/",  ":",
  102.                 "*" , "?", "\"",
  103.                 "<" , ">",  "|",
  104.                 "^", "#"
  105.                 ]
  106.     for invalid in invalids:
  107.         if invalid in [":", "|", "*", "?"]:
  108.             repl = "-"
  109.         elif invalid in "#":
  110.             repl = ""
  111.         else:
  112.             repl = "_"
  113.         text = text.replace(invalid, repl)
  114.         # elif ".com" in invalids:
  115.         #     repl = ""
  116.     return text
  117.  
  118.  
  119. # ----- ----- ----- ----- ----- -----
  120. #               Main
  121. # ----- ----- ----- ----- ----- -----
  122.  
  123. i = 0
  124. if whether_debug is True:
  125.     d(f"")
  126.     d(f"  in:", "none", "yellow")
  127.     d(f"    {user_list[0]}", "none", "yellow")
  128.  
  129. valid_filename = validate(user_list[0])
  130.  
  131. d(f"  out:", "none", "green")
  132. d(f"    {valid_filename}", "none", "green")
  133.  
  134. with open(tempfile, 'w') as file:
  135.     print(valid_filename, file=file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement