Add read and write in the same file

Signed-off-by: Rémi BERTHO <remi.bertho@dalan.fr>
This commit is contained in:
Rémi BERTHO 2017-10-24 20:12:27 +02:00
parent 0ba4b373cb
commit 1c8404e029
Signed by: dalan
GPG key ID: EE3B917931C07B64

53
SSnR.py
View file

@ -41,11 +41,11 @@ def main():
parser.add_argument('-o', '--output', help='Output file', required=False) parser.add_argument('-o', '--output', help='Output file', required=False)
parser.add_argument('-r', '--replace', help='Replace', required=False) parser.add_argument('-r', '--replace', help='Replace', required=False)
parser.add_argument('-m', '--print_nb_match', help='Print the number of match in replace', parser.add_argument('-m', '--print_nb_match', help='Print the number of match in replace',
required=False, action='store_true') required=False, action='store_true')
parser.add_argument('-c', '--ignore_case', help='Ignore the case', parser.add_argument('-c', '--ignore_case', help='Ignore the case',
required=False, action='store_true') required=False, action='store_true')
parser.add_argument('-u', '--recursive', help='Use the regex input recrusivly in the folders', parser.add_argument('-u', '--recursive', help='Use the regex input recrusivly in the folders',
required=False, action='store_true') required=False, action='store_true')
args = vars(parser.parse_args()) args = vars(parser.parse_args())
@ -60,7 +60,7 @@ def main():
return -1 return -1
# Get input # Get input
filenames = [] input_filenames = []
if args["regex_input"] is not None: if args["regex_input"] is not None:
try: try:
input_ex = compile_regex(args["regex_input"], False) input_ex = compile_regex(args["regex_input"], False)
@ -73,21 +73,21 @@ def main():
for (dirpath, dirnames, dir_filenames) in walk("."): for (dirpath, dirnames, dir_filenames) in walk("."):
for filename in dir_filenames: for filename in dir_filenames:
if input_ex.fullmatch(filename): if input_ex.fullmatch(filename):
filenames.append(os.path.join(dirpath, filename)) input_filenames.append(os.path.join(dirpath, filename))
is_file = True is_file = True
if not args["recursive"]: if not args["recursive"]:
break break
if not filenames: if not input_filenames:
print("Error: no input file") print("Error: no input file")
return -1 return -1
elif args["input"] is not None: elif args["input"] is not None:
for input_file in args["input"]: for input_file in args["input"]:
if os.path.isfile(input_file): if os.path.isfile(input_file):
is_file = True is_file = True
filenames.append(input_file) input_filenames.append(input_file)
else: else:
print("Error: file not found: " + str(args["input"])) print("Error: file not found: " + str(args["input"]))
if not filenames: if not input_filenames:
print("Error: no input file") print("Error: no input file")
return -1 return -1
elif args["string"] is not None: elif args["string"] is not None:
@ -98,27 +98,16 @@ def main():
is_file = False is_file = False
# Get output # Get output
output_files = [] output_filenames = []
if args["regex_output"] is not None: if args["regex_output"] is not None:
if input_ex is None: if input_ex is None:
print("Error: You need a regex input file to use a regex output file") print("Error: You need a regex input file to use a regex output file")
return -1 return -1
for input_filename in filenames: for input_filename in input_filenames:
try: output_filenames.append(input_ex.subn(args["regex_output"], input_filename)[0])
output_file = open((input_ex.subn(args["regex_output"], input_filename))[0], "w",
encoding="utf8")
output_files.append(output_file)
except OSError as exception:
print("Error: file not found: " + str(exception))
return -1
use_output_file = True use_output_file = True
elif args["output"] is not None: elif args["output"] is not None:
try: output_filenames.append(args["output"])
output_file = open(args["output"], "w", encoding="utf8")
output_files.append(output_file)
except OSError as exception:
print("Error: file not found: " + str(exception))
return -1
use_output_file = True use_output_file = True
else: else:
use_output_file = False use_output_file = False
@ -126,7 +115,7 @@ def main():
# Search or replace # Search or replace
file_index = 0 file_index = 0
if is_file: if is_file:
for filename in filenames: for filename in input_filenames:
try: try:
with open(filename, "r", encoding="utf8") as file: with open(filename, "r", encoding="utf8") as file:
string = file.read() string = file.read()
@ -140,10 +129,15 @@ def main():
if args["replace"] is not None: if args["replace"] is not None:
replace_string, nb_replace = replace(ex, string, args["replace"]) replace_string, nb_replace = replace(ex, string, args["replace"])
if use_output_file: if use_output_file:
output_files[file_index].write(replace_string) try:
output_file = open(output_filenames[file_index], "w", encoding="utf8")
except OSError as exception:
print("Error: file not found: " + str(exception))
return -1
output_file.write(replace_string)
print("File: " + filename) print("File: " + filename)
print(" - Number of replace: " + str(nb_replace)) print(" - Number of replace: " + str(nb_replace))
if len(output_files) > 1: if len(output_filenames) > 1:
file_index += 1 file_index += 1
else: else:
print(replace_string) print(replace_string)
@ -161,7 +155,12 @@ def main():
replace_string, nb_replace = replace(ex, string, args["replace"]) replace_string, nb_replace = replace(ex, string, args["replace"])
if use_output_file: if use_output_file:
print("Number of replace: " + str(nb_replace)) print("Number of replace: " + str(nb_replace))
output_files[0].write(replace_string) try:
output_file = open(output_filenames[file_index], "w", encoding="utf8")
except OSError as exception:
print("Error: file not found: " + str(exception))
return -1
output_file.write(replace_string)
else: else:
print(replace_string) print(replace_string)
if args["print_nb_match"]: if args["print_nb_match"]: