Skip to content

Instantly share code, notes, and snippets.

@FlyMaple
Created February 4, 2020 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FlyMaple/762b1aed845bdea95a530f268d3c8d8f to your computer and use it in GitHub Desktop.
Save FlyMaple/762b1aed845bdea95a530f268d3c8d8f to your computer and use it in GitHub Desktop.
批次轉換副檔名
import argparse
import os.path
# batch rename
def batch(work_path, old_ext, new_ext, recursive=False):
if os.path.isdir(work_path):
for file in os.listdir(work_path):
full_path = os.path.join(work_path, file)
if os.path.isdir(full_path) and recursive:
batch(full_path, old_ext, new_ext, recursive)
else:
splitext = os.path.splitext(file)
if '.' + old_ext == splitext[1]:
new_filename = splitext[0] + '.' + new_ext
full_new_filepath = os.path.join(work_path, new_filename)
try:
os.rename(full_path, full_new_filepath)
print(f'{full_path} -> {full_new_filepath}')
except:
print(f'{full_path} failed.')
# parser
def get_parser():
parser = argparse.ArgumentParser(
prog='batch_file_rename.py', description='This is batch rename function')
parser.add_argument('work_path', metavar='work_path', help='Target path')
parser.add_argument('old_ext', metavar='old_ext', help='Original ext name')
parser.add_argument('new_ext', metavar='new_ext', help='New ext name')
parser.add_argument('-r', '--recursive',
action='store_true', help='Recursive folder need or not')
return vars(parser.parse_args())
# main
def main():
args = get_parser()
print(args)
batch(args['work_path'], args['old_ext'],
args['new_ext'], args['recursive'])
print('process done!')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment