今天发布刚完成的涛哥的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)