美文网首页
python批量替换文件扩展名batch_file_rename

python批量替换文件扩展名batch_file_rename

作者: 洛丽塔的云裳 | 来源:发表于2019-10-11 20:38 被阅读0次
    方法1:直接将指定路径下后缀为py文件替换为txt
    #-*- coding: utf-8 -*-
    import os
    def batch_file_rename(path, oldext, newext):
        """ This batch renames a group of files in a given directory, once you pass the current and the new extensions. """
        file = [f for f in os.listdir(path) if not f.startswith('.') and os.path.isfile(os.path.join(path, f))]
        for afile in file:
            afname = afile.split('.')[0]
            afext = afile.split('.')[1]
            if afext == oldext:
                os.rename(os.path.join(path, afile), os.path.join(path,  afname + '.' + newext))
    
    if __name__ == '__main__':
        path = os.getcwd()
        batch_file_rename(path, 'py', 'txt')
    

    测试结果

    image.png
    方法2:通常后缀为'.xx'形式,方法1不合理,参照如下

    https://github.com/geekcomputers/Python/blob/master/batch_file_rename.py

    学习python argparse模块使用:更新代码如下:

    #-*- coding: utf-8 -*-
    import os
    import argparse
    def batch_file_rename(path, old_ext, new_ext):
        """ This batch renames a group of files in a given directory, once you pass the current and the new extensions. """
        all_file = [f for f in os.listdir(path) if not f.startswith('.') and os.path.isfile(os.path.join(path, f))]
        for file in all_file:
            split_file = os.path.splitext(file)  # spliext 用来分离文件名和拓展名
            file_name = split_file[0]
            file_ext = split_file[1]
            if file_ext == old_ext:
                os.rename(os.path.join(path, file), os.path.join(path, file_name + new_ext))
    
    def get_parser():
        """ parser params """
        parser = argparse.ArgumentParser(description='batch_file_name')
        parser.add_argument('-path', '--p', default='')
        parser.add_argument('-old_ext', '--o', default='')
        parser.add_argument('-new_ext', '--n', default='')
        args = parser.parse_args()
        path = args.p
        old_ext = args.o
        new_ext = args.n
        return path, old_ext, new_ext
    
    def main():
        """ main func """
        path, old_ext, new_ext = get_parser()
        batch_file_rename(path, old_ext, new_ext)
    
    if __name__ == '__main__':
        main()
    
    image.png

    相关文章

      网友评论

          本文标题:python批量替换文件扩展名batch_file_rename

          本文链接:https://www.haomeiwen.com/subject/axuxmctx.html