Search code examples
pythonexcelfilexlsxxlsxwriter

Overwriting data in XLSX with python


Let's assume an excel file mismatch.xlsx at a particular location in C: drive

what I want to do is first check if it exists, and if it does I want to clear all the data in it and write new data into it

if it does not exist at all I would like to create a new file "mismatch.xlsx" at a particular location and write data into it

so far I am able to create a new file "mismatch.xlsx" and write into it but if I run the program again, I get permission denied error

this is my code to write data into "mismtach.xlsx"(i have used xlsxwriter), I am assuming the solution to this is a simple 'if' loop to check for file existence, but I am new to python and I am not sure how to declare that.

with xlsxwriter.Workbook('<location>/mismtach.xlsx') as workbook:
           worksheet = workbook.add_worksheet()
           worksheet2 = workbook.add_worksheet()
           worksheet3 = workbook.add_worksheet()
           
           for row_num , data in enumerate(mismatch_true):
                worksheet.write_row(row_num, 0, data)  
           for row_num2 , data2 in enumerate(semi):
                worksheet2.write_row(row_num2, 0, data2) 
           for row_num3 , data3 in enumerate(quarter):
               worksheet3.write_row(row_num3, 0, data3) 

ERROR: xlsxwriter.exceptions.FileCreateError: [Errno 13] Permission denied: '(location)/mismtach.xlsx'


Solution

  • Does this meet what you are after?

    import os
    import xlsxwriter
    
    # Excel File Name
    xlfile = "mismtach.xlsx"
    
    # Excel File Exits Then Remove
    if os.path.exists(xlfile):
        os.remove(xlfile)
    
    # Create a workbook and add a worksheet.
    workbook = xlsxwriter.Workbook(xlfile)
    worksheet = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()
    worksheet3 = workbook.add_worksheet()
    
    # Iterate over the data and write it out row by row.
    (your data)
    
    # Close Workbook.
    workbook.close(xlfile)