Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import fileinput
  2. import argparse
  3. import os
  4.  
  5. parser = argparse.ArgumentParser()
  6. source_group = parser.add_mutually_exclusive_group(required=True)
  7. source_group.add_argument('-d', '--directory', help='Directory to replace ALL files located there')
  8. source_group.add_argument('-f', '--file', help='File to replace characters')
  9. parser.add_argument('-s', '--search', help='Search all occurrences to replace', default='\x01')
  10. parser.add_argument('-r', '--replace', help='Replaces this characters', default='\x01')
  11. parser.add_argument('-e', '--encoding', help='Encoding (default: utf-8)', default='utf-8')
  12.  
  13. args = parser.parse_args()
  14.  
  15. def replace_file(filename, search_str, replace_str, encoding):
  16. with open(filename, 'r', encoding=encoding) as file:
  17. filedata = file.read()
  18.  
  19. filedata = filedata.replace(search_str, replace_str)
  20.  
  21. with open(filename, 'w', encoding=encoding) as file:
  22. file.write(filedata)
  23.  
  24.  
  25. if os.path.exists(args.directory):
  26. for filename in os.listdir(args.directory):
  27. filepath = os.path.join(args.directory, filename)
  28. replace_file(filepath, args.search, args.replace, args.encoding)
  29. elif os.path.exists(args.file):
  30. replace_file(args.file, args.search, args.replace, args.encoding)
  31. else:
  32. raise Exception('File or directory do not exists')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement