大量rename文件

author = 'Craig Richards'
version = '1.0'

import argparse
import os

批量重命名 # 工作目录, 旧文件, 新文件

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: 以列表的形式 列出工作目录的文件 ['0.txt', '2.txt', 'batch_file_rename.py']
# files = os.listdir(work_dir)
# 遍历工作目录的文件
for filename in os.listdir(work_dir):
# Get the file extension
# 分离文件名和扩展名 得到元组
# ('0', '.txt')
# ('2', '.txt')
# ('batch_file_rename', '.py')
split_file = os.path.splitext(filename)
# Unpack tuple element
# 将元组各值赋值给两个变量
# 文件名, 文件格式
root_name, file_ext = split_file
# 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 = root_name + new_ext

        # Write the files
        # 重命名文件 ( 1.原文件名  2.新文件名 )
        os.rename(
            # 拼接路径和文件名
            os.path.join(work_dir, filename),
            os.path.join(work_dir, newfile)
        )
print("rename is done!")
print(os.listdir(work_dir))

获取解析

def get_parser():
# 使用argparse方法的ArgumentParser生成实例
# 更改工作目录中文件的扩展名
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.
:return:
"""
# 增加命令行参数
# 将get_parser()获取的值存入parser中
parser = get_parser()
# vars()函数返回对象object的属性和属性值的字典对象
args = vars(parser.parse_args())

# Set the variable work_dir with the first argument passed
# 设置变量work_dir 并传递第一个参数
work_dir = args['work_dir'][0]
# Set the variable old_ext with the second argument passed
# 设置变量old_ext 并传递第二个参数
old_ext = args['old_ext'][0]

# 如果old_ext的第一个参数不是'.'
if old_ext[0] != '.':
    # 给old_ext的前面加个'.'
    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()

#

猜你喜欢

转载自www.cnblogs.com/sunnywillow/p/13388136.html