Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active October 14, 2015 07:39
Show Gist options
  • Save dogrunjp/5fd26934f15131c290ff to your computer and use it in GitHub Desktop.
Save dogrunjp/5fd26934f15131c290ff to your computer and use it in GitHub Desktop.
指定したディレクトリのファイル内の文字列を一括して変換するPythonスクリプト。静的ファイルの中身の置き換え作業がたまに発生するのですが、sedを使い慣れないため、Pythonで作っておきました。

使い方

$ python easyreplace.py [対象とするディレクトリ] "置換する対象文字列" "置換後の文字列" [-r] [-c]

  • -r :オプション 対象文字列を正規表現で記述
  • -c :オプション 別名で保存(頭に_を付けます)
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import argparse
import re
def main():
parser = argparse.ArgumentParser(description='how to use')
parser.add_argument('path_src', action='store')
parser.add_argument('str_src', action='store')
parser.add_argument('str_dst', action='store')
parser.add_argument('--reg', '-r', dest='reg',action='store_true', help='use regular expression')
parser.add_argument('--copy', '-c', dest='cp',action='store_true', help='save as new file')
args = parser.parse_args()
file_list = os.listdir(args.path_src)
file_path = args.path_src
for file in file_list:
if os.path.isdir(os.path.join(file_path, file)):
print(file , "is directory")
else:
f = open(file_path + "/" + file)
src = f.read()
f.close()
if args.reg:
rsrc = r'%s' % args.str_src
pattern = re.compile(rsrc)
dst = pattern.sub(args.str_dst, src)
else:
dst = src.replace(args.str_src, args.str_dst)
if args.cp:
filename = file_path + "/" + file
else:
filename = file_path + "/" + file
f = open(filename, 'w')
f.write(dst)
f.close()
# python easyreplace.py [対象とするディレクトリ] [置換する対象文字列] [置換後の文字列] [-r] [-c]
# -r :オプション 対象文字列を正規表現で記述
# -c :オプション 別名で保存(頭に_を付けます)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment