Here is one approach to checking if the file can be created in a try/except block.
For completeness it also shows how to check if the file is writeable at creation/close time (which might suit your purposes better):
import xlsxwriter
filename = 'test.xlsx'
# Try to opene() the file in a loop so that if there is an exception, such as
# if the file is open in Excel, we can ask the user to close the file.
while True:
try:
filehandle = open(filename, 'w')
filehandle.close()
except Exception as e:
decision = input("Could open file: %s\n"
"Please close the file if it is open in Excel.\n"
"Try to write file again? [Y/n]: " % e)
if decision != 'n':
continue
else:
exit
break
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello world')
# Try to close() the file in a loop so that we can catch the exception.
# Note the XlsxWriter specific exception.
while True:
try:
workbook.close()
except xlsxwriter.exceptions.FileCreateError as e:
decision = input("Exception caught in workbook.close(): %s\n"
"Please close the file if it is open in Excel.\n"
"Try to write file again? [Y/n]: " % e)
if decision != 'n':
continue
break
Note, this approach introduces a potential TOCTOU error but that may not be an issue for a simple use case.