预先测试xlsxwriter是否能够在Windows下写入目标文件

问题描述

我编写了一个小程序,使用xlsxwriter在Windows上平凡地将大量数据转换为Excel工作表,然后在Excel中手动将其打开以进行进一步分析。

如果我已经在Excel中打开了文件却忘记了显式关闭文件,则xlsxwriter在尝试将内存表保存到磁盘且权限被拒绝时会失败。我了解这是Windows而不是Linux的行为方式。

我想在程序开始时检测到该文件已经在Excel中打开,所以我很快就会失败,而不是过一会儿。

如何在Python 3.8.5中检测到这一点?

解决方法

这是一种检查文件是否可以在try / except块中创建的方法。

为了完整起见,它还显示了如何在创建/关闭时检查文件是否可写(这可能更适合您的目的):

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

请注意,这种方法会带来潜在的TOCTOU错误,但对于简单的用例而言可能不是问题。