python批量替换文件扩展名batch_file_rename

2019-10-11  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读