鱼C论坛

 找回密码
 立即注册
查看: 1384|回复: 2

新手问一个关于批量重命名指定目录下面所有文件的后缀名的程序问题

[复制链接]
发表于 2019-7-19 14:30:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
下面是我在网上看到的一个完整代码:
import os
import argparse


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
        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)
            )


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)
    work_dir = "/Users/Glassy Sky/Desktop/text/"
    old_ext = "pdf"
    new_ext = "docx"


if __name__ == '__main__':
    main()

运行时出现下面错误:
usage: text.py [-h] WORK_DIR OLD_EXT NEW_EXT
text.py: error: the following arguments are required: WORK_DIR, OLD_EXT, NEW_EXT

我看了好久都不知道哪里错了,期待路人大佬帮我指点一下
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-7-19 15:41:48 | 显示全部楼层
应该是你调用错了   这个目测是需要输入命令行参数的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-7-19 16:34:34 | 显示全部楼层
wp231957 发表于 2019-7-19 15:41
应该是你调用错了   这个目测是需要输入命令行参数的

那该怎么修改呢,求指点
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-17 01:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表