Search code examples
pythonpandaswindowserror-handlingfile-permissions

How do I fix this error "The process cannot access the file because it is being used by another process"?


This is the snippet of the code which throws the error:

writer=pd.ExcelWriter('C:\\Users\\aji/Curve.xlsx',engine='openpyxl')   
if os.path.exists('C:\\Users\\aji/Curve.xlsx'):
        os.remove('C:\\Users\\aji/Curve.xlsx')

I got this error message:

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

I'm pretty sure the file in the path is not open. What is causing this problem and how do I fix it?


Solution

  • I don't think you're writing to the file properly. As a result, your writer has the file open.

    According to the documentation:

    The writer should be used as a context manager. Otherwise, call close() to save and close any opened file handles.

    Try this instead (assuming the DataFrame you wish to write is stored in df):

    with pd.ExcelWriter('C:\\Users\\aji/Curve.xlsx', engine='openpyxl') as writer:
        df.to_excel(writer)
    
    if os.path.exists('C:\\Users\\aji/Curve.xlsx'):
        os.remove('C:\\Users\\aji/Curve.xlsx')
    

    There are other good examples in the link I provided above. I suggest reviewing them in case another is a better fit for your use case.

    And as a commenter suggested, mixing slashes is confusing. Either use backslashes everywhere, or forward slashes everywhere. But that shouldn't technically cause problems, it's just distracting.