Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import fileinput
- import argparse
- import os
- parser = argparse.ArgumentParser()
- source_group = parser.add_mutually_exclusive_group(required=True)
- source_group.add_argument('-d', '--directory', help='Directory to replace ALL files located there')
- source_group.add_argument('-f', '--file', help='File to replace characters')
- parser.add_argument('-s', '--search', help='Search all occurrences to replace', default='\x01')
- parser.add_argument('-r', '--replace', help='Replaces this characters', default='\x01')
- parser.add_argument('-e', '--encoding', help='Encoding (default: utf-8)', default='utf-8')
- args = parser.parse_args()
- def replace_file(filename, search_str, replace_str, encoding):
- with open(filename, 'r', encoding=encoding) as file:
- filedata = file.read()
- filedata = filedata.replace(search_str, replace_str)
- with open(filename, 'w', encoding=encoding) as file:
- file.write(filedata)
- if os.path.exists(args.directory):
- for filename in os.listdir(args.directory):
- filepath = os.path.join(args.directory, filename)
- replace_file(filepath, args.search, args.replace, args.encoding)
- elif os.path.exists(args.file):
- replace_file(args.file, args.search, args.replace, args.encoding)
- else:
- raise Exception('File or directory do not exists')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement