From bd78fcf8db5a957169d592afd04dd217b5da69d1 Mon Sep 17 00:00:00 2001 From: "Frank M. Taylor" Date: Mon, 19 Sep 2022 11:40:15 -0500 Subject: [PATCH] adds error handling and writes a tad safer --- xlstojson.py | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/xlstojson.py b/xlstojson.py index 1bdf8e0..0750400 100644 --- a/xlstojson.py +++ b/xlstojson.py @@ -1,19 +1,24 @@ #!/usr/bin/python3.10 -import json -import os.path +import json, os, sys from xlsx_reader import get_workbook, get_workbook_data def main(): ''' The CLI / output task. ''' - filename = input("Enter the path to the filename -> ") - if os.path.isfile(filename): - workbook = get_workbook(filename) - workbook_data = get_workbook_data(workbook) - output = \ - open((filename.replace("xlsx", "json")).replace("xls", "json"), "w+", encoding="utf-8") - output.write(json.dumps(workbook_data, sort_keys=True, indent=2, separators=(',', ": "))) - output.close() - print (f"{output.name} was created") + source_file = input("Enter the path to the filename -> ") + if os.path.isfile(source_file): + pathname = os.path.splitext(source_file) + file_name = pathname[0].split('/')[-1] + try: + output_file_name = file_name + '.json' + workbook = get_workbook(source_file) + workbook_data = get_workbook_data(workbook) + with open(output_file_name, 'w+', encoding="utf-8") as output_file: + output_file.write(json.dumps(workbook_data, sort_keys=True, indent=2, separators=(",", ": "))) + print (f"{output_file.name} was created") + except Exception as error: + print("some error occured") + print(error) + sys.exit(2) else: print ("Sorry, that was not a valid filename")