So I am trying to deal with an encoding/decoding error that I get sometimes. Usually it is fixed by encoding in mbcs, but I wanted to also give other situations to try for the same exception. However, I only want it to keep trying in error handling until it hits a situation without an exception.
My problem is that whether I try to use functions, multiple blocks ending with except: pass, or nested try/excepts, it always runs correctly but still gives me my final error message anyways: "'Unable to Encode most likely due to special characters.'". Can anyone help me understand how I can make the error handling stop and not continue on if there is no exception? I realize there might be better ways to do this anyways, but for a learning perspective, why am I still getting the final message and how can it be avoided if my code ran with no exception.
InputPath = ''
OutputPath = ''
def ConvertButtonPress():
try:
if InputPath == '' or OutputPath == '':
RunButton['state'] = "disabled"
else:
RunButton['state'] = "normal"
with open(InputPath) as CSVInput:
with open(OutputPath, 'w', newline='') as TXTOutput:
reader = csv.DictReader(CSVInput, delimiter=',')
writer = csv.DictWriter(TXTOutput, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
except (UnicodeEncodeError, UnicodeDecodeError):
ConvertButtonPress_mbcs()
def ConvertButtonPress_mbcs():
try:
if InputPath == '' or OutputPath == '':
RunButton['state'] = "disabled"
else:
RunButton['state'] = "normal"
with open(InputPath, encoding="mbcs") as CSVInput:
with open(OutputPath, 'w', newline='') as TXTOutput:
reader = csv.DictReader(CSVInput, delimiter=',')
writer = csv.DictWriter(TXTOutput, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
except (UnicodeEncodeError, UnicodeDecodeError):
ConvertButtonPress_utf8()
def ConvertButtonPress_utf8():
try:
if InputPath == '' or OutputPath == '':
RunButton['state'] = "disabled"
else:
RunButton['state'] = "normal"
with open(InputPath, encoding="utf-8") as CSVInput:
with open(OutputPath, 'w', newline='') as TXTOutput:
reader = csv.DictReader(CSVInput, delimiter=',')
writer = csv.DictWriter(TXTOutput, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
except (UnicodeEncodeError, UnicodeDecodeError):
RunButton['text'] = 'Unable to Encode most likely due to special characters.'