User can upload both UTF-8 and UTF-16 CSV file which is the attendance file of Microsoft teams that they download from there. To handle the case I have written the following code but there is some strange issue that I am not able to fix.
excel_file = request.FILES['excel-file']
try:
print('try case')
df = pd.read_csv(excel_file)
csv_type = 'a'
print(df)
except UnicodeDecodeError:
print('except case')
from io import BytesIO
df = pd.read_csv(BytesIO(excel_file.read().decode('UTF-16').encode('UTF-8')), sep='\\')
csv_type = 'b'
print(df)
except Exception as e:
print("Incorrect CSV file format", e)
Here first 'try case' handle the UTF-8 and 'except case' handle the UTF-16 CSV file. Both case work fine if I run them separately, But when I put them in try except block then the code fails. Here in the above code UTF-8 case works but UTF-16 gives No columns to parse from file error. Now if I move the except code to try then UTF-16 will work but it will also run for UTF-8 giving wrong data. So how can I handle this case haven't found any way to get file encoding also.