本期主题: python重命名文件脚本,批量修改某一文件夹下的后缀名
1.代码
import argparse
import os
def batch_rename(work_dir, old_ext, new_ext):
for filename in os.listdir(work_dir):
print(filename)
splite_file = os.path.splitext(filename)
root_name, file_ext = splite_file
if old_ext == file_ext:
newfile = root_name + new_ext
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():
parser = argparse.ArgumentParser(
description="use to change name in a directory"
)
parser.add_argument(
"work_dir",
metavar="WORK_DIR",
type=str,
nargs=1,
help="the work dir",
)
parser.add_argument(
"old_ext",
metavar="OLD_EXT",
type=str,
nargs=1,
help="old ext name",
)
parser.add_argument(
"new_ext",
metavar="NEW_EXT",
type=str,
nargs=1,
help="new ext name",
)
return parser
def main():
parser = get_parser()
args = vars(parser.parse_args())
work_dir = args["work_dir"][0]
old_ext = args["old_ext"][0]
if old_ext and old_ext[0] != ".":
old_ext = "." + old_ext
new_ext = args["new_ext"][0]
if new_ext and new_ext[0] != ".":
new_ext = "." + new_ext
batch_rename(work_dir, old_ext, new_ext)
if __name__ == "__main__":
main()
2.使用
//运行时提示:
jason@ubuntu:~/WorkSpace/5.Python/0.batch_rename$ python3 batch_rename.py -h
usage: batch_rename.py [-h] WORK_DIR OLD_EXT NEW_EXT
use to change name in a directory
positional arguments:
WORK_DIR the work dir
OLD_EXT old ext name
NEW_EXT new ext name
optional arguments:
-h, --help show this help message and exit
work_dir是工作目录 old_ext是旧的扩展名 new_ext是需要转换的新的扩展名
在rename_dir目录下有3个文件
jason@ubuntu:~/WorkSpace/5.Python/0.batch_rename$ ls rename_dir/ a.tmp b.tmp c.tmp jason@ubuntu:~/WorkSpace/5.Python/0.batch_rename$ python3 batch_rename.py ./rename_dir .tmp .txt c.tmp b.tmp a.tmp rename is done! [‘c.txt’, ‘a.txt’, ‘b.txt’]
3.简单解析
argparse实际上是python标准库中的命令行解析模块。 参考我们使用的ls命令
- ls即使在运行时没提供任何选项,默认会输出当前文件夹包含的文件和文件夹;
- ls xxx,其中的这个xxx代表是位置参数
- ls -l,这个-l是可选参数
我们上面的例子中,python脚本后面就是跟的三个位置参数,关于argparse的详细解释,参考官方教程: Argparse 教程
|