Advertisement
lexquarkie

obama

Dec 4th, 2014
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: UTF-8 -*-
  3.  
  4. import sys
  5. import re
  6. from os import listdir
  7.  
  8. def arg_parse():
  9.     global source_pattern
  10.     global repl_pattern
  11.     global path
  12.  
  13.     if len(sys.argv)>=3:
  14.         path = str(sys.argv[1])
  15.         if not path.endswith('/'): #дополняем путь закрывающим слэшем,
  16.             path += '/'           #если он отсутствует
  17.         source_pattern = str(sys.argv[2])
  18.         if len(sys.argv)>3:
  19.             repl_pattern = str(sys.argv[3])
  20.         else:
  21.             repl_pattern = ''
  22.     else:  
  23.         error()
  24. def error():
  25.     print('Usage: python3 obama.py PATH SOURCE_PATTERN REPLACE_PATTERN')
  26.     exit()
  27.  
  28.  
  29. def prompt(path, source_pattern, repl_pattern):
  30.     if repl_pattern == '':
  31.         zam = 'EMPTY PATTERN, just delete source text'
  32.     else:
  33.         zam = repl_pattern
  34.     submit = input('Are you sure you want to replace "' + source_pattern +'"  for "' + zam + '" in all files of ' + path + ' ?')
  35.     if submit == 'Y' or submit == 'y':
  36.         replace(path, source_pattern, repl_pattern)
  37.  
  38. def replace(path, source_pattern, repl_pattern):
  39.     for f in listdir(path):
  40.         fh = file(f, 'r')
  41.         output = re.sub(source_pattern, repl_pattern, fh.read())
  42.         fh.close()
  43.  
  44.         f_out = file(f, 'w')
  45.         f_out.write(output)
  46.         print(path + f + ' is changed and saved')
  47.         f_out.close()
  48.  
  49.  
  50. if __name__ == "__main__":
  51.     arg_parse()
  52.     prompt(path, source_pattern, repl_pattern)
  53.     replace(path, source_pattern, repl_pattern)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement