Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- # -*- coding: UTF-8 -*-
- import sys
- import re
- from os import listdir
- def arg_parse():
- global source_pattern
- global repl_pattern
- global path
- if len(sys.argv)>=3:
- path = str(sys.argv[1])
- if not path.endswith('/'): #дополняем путь закрывающим слэшем,
- path += '/' #если он отсутствует
- source_pattern = str(sys.argv[2])
- if len(sys.argv)>3:
- repl_pattern = str(sys.argv[3])
- else:
- repl_pattern = ''
- else:
- error()
- def error():
- print('Usage: python3 obama.py PATH SOURCE_PATTERN REPLACE_PATTERN')
- exit()
- def prompt(path, source_pattern, repl_pattern):
- if repl_pattern == '':
- zam = 'EMPTY PATTERN, just delete source text'
- else:
- zam = repl_pattern
- submit = input('Are you sure you want to replace "' + source_pattern +'" for "' + zam + '" in all files of ' + path + ' ?')
- if submit == 'Y' or submit == 'y':
- replace(path, source_pattern, repl_pattern)
- def replace(path, source_pattern, repl_pattern):
- for f in listdir(path):
- fh = file(f, 'r')
- output = re.sub(source_pattern, repl_pattern, fh.read())
- fh.close()
- f_out = file(f, 'w')
- f_out.write(output)
- print(path + f + ' is changed and saved')
- f_out.close()
- if __name__ == "__main__":
- arg_parse()
- prompt(path, source_pattern, repl_pattern)
- replace(path, source_pattern, repl_pattern)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement