0

I am trying to catch an error when writing an excel file, for example when the file is already open:

import pandas as pd
import xlsxwriter

test = "2020/04/02|17:50:33|Conversion succeeded (SemanticProtocolConverter): TEST/Neuro/Neuro/Dot Tete VE11/AX T1 mprage post|TE: 3.24 --> 3.02 ms; Echo Spacing: 7.84 --> 7.62 ms; Coil Selection: Manual --> ACS All but spine|22808"
test2 = test.split("|")

df = pd.DataFrame(test2)
df = df.transpose()

outDF = test2
outXLSX = pd.ExcelWriter("test.xlsx", engine='xlsxwriter')
df.to_excel(outXLSX, 'Test', index=False)
try:
    outXLSX.save()
except IOError:
    print("Cannot open the file")

print("done")

The problem is that it doesn't catch the error. How can I make sure I can write to the file?

Thanks, Bart

  • Possible duplicate of [this question](https://stackoverflow.com/questions/6825994/check-if-a-file-is-open-in-python). You could try renaming the file... – gnodab Apr 09 '20 at 18:53

2 Answers2

0

If it is not catching the error, that means the Exception which you defined in your try\except statement is not exception that it is throwing. You can try a more general Exception, it might throw an error that might help you solve the issue.

try:
    outXLSX.save()

except Exception as e:
    print(e)

finally:
    print("done")


0

This error that you are getting is coming from xlsxwriter. To catch this error you should use this block of code:

try:
    outXLSX.save()
except xlsxwriter.exceptions.FileCreateError:
    print("Can not save because file is open. Close it and retry.")
except Exception as error:
    print(error)

Have a look at xlsxwriter's documentation here .

Dimitris Thomas
  • 1,363
  • 9
  • 14