python-argparse批量修改后缀名-batch_file_rename.py

#!/bin/usr/env python3

__author__ = 'nxz'

import os
import argparse

def batch_rename(work_dir, old_ext, new_ext):
    """
    批量将指定文件夹下的后缀名修改为新的后缀名
    """
    for filename in os.listdir(work_dir):
        # 获取文件名后缀
        split_file = os.path.splitext(filename)
        file_ext = split_file[1]
        # 当后缀和给出的old_ext相同时,修改文件名
        if old_ext == file_ext:
            # return changed name of the file with new extension
            newfile = split_file[0] + new_ext
            # write the files
            os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile))

def get_parse():
    parser = argparse.ArgumentParser(description="批量修改指定文件夹下的文件后缀")
    parser.add_argument("work_dir", metavar="WORK_DIR", type=str, nargs=1,
                        help="要修改后缀的文件夹路径")
    parser.add_argument("old_ext", metavar="OLD_EXT", type=str, nargs=1, help="旧后缀")
    parser.add_argument("new_ext", metavar="NEW_EXT", type=str, nargs=1, help="新后缀")
    return parser

def main():
    parser = get_parse()
    args = vars(parser.parse_args())
    print(args)
    work_dir = args['work_dir'][0]
    old_ext = args['old_ext'][0]
    new_ext = args['new_ext'][0]
  #使用了python中的切片 例如: a[0:2]
if (old_ext[0] != '.'): old_ext = '.' + old_ext if (new_ext[0] != '.'): new_ext = '.' + new_ext batch_rename(work_dir, old_ext, new_ext) if __name__ == '__main__': main()

使用:python batch_file_rename.py --help 

posted @ 2019-04-03 15:41  xj-record  阅读(411)  评论(0编辑  收藏  举报