Python:批处理文件后缀名 batch_file_rename.py(源程序+详细讲解)

# batch_file_rename.py
# Created: 6th August 2012
# coding:utf-8

"""
This will batch rename a group of files in a given directory,
once you pass the current and new extensions
"""

# just checking
__author__ = 'Craig Richards'
__version__ = '1.0'

import os
import argparse
"""
    python3中argparse模块
    1、定义:argparse是python标准库里面用来处理命令行参数的库
    
    2、命令行参数分为位置参数和选项参数:
    位置参数就是程序根据该参数出现的位置来确定的
    如:[root@openstack_1 /]# ls root/    #其中root/是位置参数
    选项参数是应用程序已经提前定义好的参数,不是随意指定的
    如:[root@openstack_1 /]# ls -l    # -l 就是ls命令里的一个选项参数
    3、使用步骤:
    
    (1)import argparse    首先导入模块
    (2)parser = argparse.ArgumentParser()    创建一个解析对象
    (3)parser.add_argument()    向该对象中添加你要关注的命令行参数和选项
    (4)parser.parse_args()    进行解析
    4、argparse.ArgumentParser()方法参数须知:一般我们只选择用description
    
    prog=None     - 程序名
    
    description=None,    - help时显示的开始文字
    epilog=None,     - help时显示的结尾文字
    parents=[],        -若与其他参数的一些内容一样,可以继承
    formatter_class=argparse.HelpFormatter,     - 自定义帮助信息的格式
    prefix_chars='-',    - 命令的前缀,默认是‘-’
    fromfile_prefix_chars=None,     - 命令行参数从文件中读取
    argument_default=None,    - 设置一个全局的选项缺省值,一般每个选项单独设置
    conflict_handler='error',     - 定义两个add_argument中添加的选项名字发生冲突时怎么处理,默认处理是抛出异常
    add_help=True    - 是否增加-h/--help选项,默认是True)
    5、add_argument()方法参数须知:
    
    name or flags...    - 必选,指定参数的形式,一般写两个,一个短参数,一个长参数
"""

def batch_rename(work_dir, old_ext, new_ext):
    """
    This will batch rename a group of files in a given directory,
    once you pass the current and new extensions
    """
    # files = os.listdir(work_dir)
    for filename in os.listdir(work_dir):
        # Get the file extension #os.path.splitext 用来分离文件名和扩展名,返回(fname,fextension)
        split_file = os.path.splitext(filename)
        file_ext = split_file[1]
        # Start of the logic to check the file extensions, if old_ext = file_ext
        if old_ext == file_ext:
            # Returns changed name of the file with new extention
            newfile = split_file[0] + new_ext

            # Write the files
            os.rename(
                os.path.join(work_dir, filename),
                os.path.join(work_dir, newfile)
            )
            """
                os.path.join()函数:连接两个或更多的路径名组件
                
                1.如果各组件名首字母不包含’/’,则函数会自动加上
                
                2.如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃
                
                3.如果最后一个组件为空,则生成的路径以一个’/’分隔符结尾
            """


def get_parser():
    parser = argparse.ArgumentParser(description='change extension of files in a working directory')
    parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1,
                        help='the directory where to change extension')
    parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension')
    parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension')
    return parser


def main():
    """
    This will be called if the script is directly invoked.
    """
    # adding command line argument
    parser = get_parser()
    args = vars(parser.parse_args())

    # Set the variable work_dir with the first argument passed
    work_dir = args['work_dir'][0]
    # Set the variable old_ext with the second argument passed
    old_ext = args['old_ext'][0]
    if old_ext[0] != '.':
        old_ext = '.' + old_ext
    # Set the variable new_ext with the third argument passed
    new_ext = args['new_ext'][0]
    if new_ext[0] != '.':
        new_ext = '.' + new_ext

    batch_rename(work_dir, old_ext, new_ext)


if __name__ == '__main__':
    main()
"""
    测试成功:在命令行使用语句:
    python3 /Users/dl/Documents/github\ download/Python-master/已读/batch_file_rename.py /Users/dl/Documents/github\ download/Python-master/已读/ .txt .py
    注意:如果不使用python3会报语法错误,注释里有中文,会报:
    SyntaxError: Non-ASCII character '\xe4' in file /Users/dl/Documents/github download/Python-master/已读/batch_file_rename.py on line 17, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
"""

 

你可能感兴趣的:(自我学习归纳)