chronossc/openpyxl

close() of read only workbook doesn't allow me to delete the file

Closed this issue · 1 comments

When I run this code:

import openpyxl
import os
import shutil
import tempfile

old_path = "C:\\Users\\x\\spectral_work\\2019-GRESB-Asset-Spreadsheet.xlsx"
excel_path = "C:\\Users\\x\\spectral_work\\my_book.xlsx"

try:
    shutil.copy2(old_path, excel_path)
    gresb_book = openpyxl.load_workbook(excel_path, read_only=True)

    building_characteristics_sheet = gresb_book.worksheets[3]
    row = 8
    while building_characteristics_sheet.cell(row, 3).value is not None:
        row += 1

    gresb_book.close()
    
finally:
    os.remove(excel_path)

I get this error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\x\\spectral_work\\my_book.xlsx'

Do you have any ideas of how I could fix this?

If I remove the read_only=True argument and the .close() statement it works. Furthermore if I remove the for loop it runs fine without errors. However after accessing the workbook it doesn't allow me to delete the copy.

Cheers,
Dylan.

@dylanmorroll As a heads up, Openpyxl development was moved here.