涛哥的Python脚本工具箱之批量替换目录所有指定扩展名的文件中的指定字符串

今天发布刚完成的涛哥的Python脚本工具箱之批量替换目录所有指定扩展名的文件中的指定字符串,命令行参数处理改用目前比较好用的argparse库,Python代码如下:


#!/usr/bin/python2.7
# -*- encoding: UTF-8 -*-
# Copyright 2014 offbye@gmail.com


"""replace old string with new string from all files in path

批量替换目录所有指定扩展名的文件中的指定字符串

Usage: python replace_str.py -o OLD -n NEW -p YOUR_PATH   -e FILE_EXTENSION
"""

__author__ = ['"Xitao":<offbye@gmail.com>']

import sys
import os
import re
import shutil
from argparse import ArgumentParser


def replace_path(p, old, new, suffix='txt'):
    # 传递路径及两个字符串作为参数
    workdir = p
    os.chdir(workdir)
    cwd = os.getcwd()
    dirs = os.listdir(cwd)
    for tmp in dirs:
        path = os.path.join(cwd, tmp)
        #print 'path=', path
        #如果是文件
        if os.path.isfile(path):
            #判断文件扩展名
            if os.path.splitext(tmp)[1][1:] == suffix:
                with open(path) as f:
                    data = f.read()
                #print data
                data_new = re.sub(old, new, data)
                if data_new != data:
                    temp = path + ".bak"
                    with open(temp, 'wb') as fnew:
                        fnew.write(data_new)
                        shutil.move(temp, path)
                    print("replace file {0} to {1} in {2}".format(old, new, path))

                    #如果是路径,递归
        elif os.path.isdir(path):
            print("Enter dir: " + path)
            replace_path(path, old, new, suffix)


if __name__ == "__main__":
    p = ArgumentParser(usage='python replace_str.py -o OLD -n NEW -p YOUR_PATH -e FILE_EXTENSION ',
                       description='replace old string with new string from all specific extension files in path')
    p.add_argument('-o', '--old', default='', help='old string want to be replaced')
    p.add_argument('-n', '--new', default='', help='new string')
    p.add_argument('-p', '--path', default="./", help='target directory')
    p.add_argument('-e', '--ext', default="txt", help='target file extension')

    # 这个函数将认识的和不认识的参数分开放进2个变量中
    args, remaining = p.parse_known_args(sys.argv)
    print(args)
    print(remaining)

    if args.old and args.new:
        print(args.old)
        replace_path(args.path, args.old, args.new, args.ext)




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

offbye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值