Last active
February 11, 2023 02:38
-
-
Save knwng/775d8d20c502b3992bc4f91f98e2680d to your computer and use it in GitHub Desktop.
将全大写的文件名改为正常的标题
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import glob | |
import argparse | |
import typing | |
from concurrent.futures import ThreadPoolExecutor | |
parser = argparse.ArgumentParser() | |
parser.add_argument('files', nargs='+', type=str) | |
parser.add_argument('-d', '--dry-run', dest='dry_run', action='store_true') | |
parser.add_argument('-r', '--recursive', action='store_true') | |
args = parser.parse_args() | |
args.files = typing.cast(typing.List[str], args.files) | |
def worker(path): | |
fn: str = os.path.basename(path) | |
fn_wo_suffix, suffix = fn.rsplit('.', maxsplit=1) | |
if fn_wo_suffix.isascii() and fn_wo_suffix.isupper(): | |
new_path = os.path.join(os.path.dirname(path), f'{fn_wo_suffix.title()}.{suffix}') | |
if not args.dry_run: | |
os.rename(path, new_path) | |
print(f'rename {path} to {new_path}') | |
paths = [] | |
if args.recursive: | |
for path in args.files: | |
if os.path.isdir(path): | |
paths += filter(os.path.isfile, | |
glob.iglob(os.path.join(path, '**/*'), recursive=True)) | |
else: | |
paths.append(path) | |
else: | |
paths = args.files | |
if __name__ == '__main__': | |
with ThreadPoolExecutor(max_workers=min(len(paths), os.cpu_count() + 4)) as p: | |
p.map(worker, paths) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment