I have a mixed dataset which I am attempting to handle all cases by using try/except
blocks. Essentially I try the first case, if that fails then I try the next case in the except block, and so on.
It was working OK until I got to 10 levels of except. Is this a thing in Python.
I cannot find a definitive answer to this question. I suspect I am writing really bad code.
I give actual code in the first try block only:
try:
logf.write(f'Processing Type 8...\n')
with open(filename, 'r') as las_file:
l = las_file.readlines()
# drop the header lines and start reading the file from the header row (indicated by ~A)
lasdata = [x.replace('\n', '').split() for x in list(
dropwhile(lambda x: '~A' not in x, l))]
# delete ~A from the header row
del lasdata[0][0]
las_df = pd.DataFrame(lasdata)
# now set column names as header
new_header = [
'DEPTH',
'GR',
'CALI',
'BRD',
'LSD',
'SSD',
]
las_df = las_df[1:]
las_df.columns = new_header
# add hole id as column
las_df['BHID'] = hole
las_df['filename'] = filename
# make a copy and drop unwanted columns
las_df = las_df[[
'filename',
'BHID',
'DEPTH',
'LSD',
'SSD',
'GR',
'CALI']].copy()
# append each hole in loop
type8_df = type8_df.append(las_df)
# write success to log file
logf.write(f'Type 8: Hole {hole} Processed OK\n')
# output to CSV file without the pandas index column
type8_df.to_csv(path_or_buf='.\\type_8.csv', index=False)
except KeyError as e:
try:
do_something()
except KeyError as e:
try:
do_something()
except KeyError as e:
try:
do_something()
except KeyError as e:
try:
do_something()
except Exception as e:
logfile.write(e)
and so on - ten levels deep
This is the error message:
Fatal Python error: XXX block stack overflow Current thread 0x000027a8 (most recent call first): File "e:/python/geology/las_data/las_converter.py", line 398 in las_converter File "e:/python/geology/las_data/las_converter.py", line 471 in
I have more than ten KeyError cases to handle. how do I do this?
UPDATE
I have refactored this where now I generate a list of all of the header/column name cases I have to deal with - when processing some directories of files I get up to 50 cases so my try/except approach was never going to work. I then process each file using an if statement to match by type then process.
Thanks all I learned a lot.