0

When I run a Pythonscript I get the PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: (filename)

First I run a SQL-script and write the result to excel. Then I want to convert the xslx-file to a xlsb-file and remove the xslx.

My code after the to_excel and writer.save:

naam = Export_locatie + 'Map' + "\\" +'Name' + str(date.today())
try:
  os.remove(naam + '.xlsb') 
except:
  print("file not available")

excel = win32.Dispatch('Excel.Application')
wb = excel.Workbooks.Open(Bestands_naam)

#Activate second sheet
excel.Worksheets(1).Activate()

#Autofit column in active sheet
excel.ActiveSheet.Columns.AutoFit()

excel.ActiveSheet.Columns.AutoFilter()

wb.SaveAs(naam + '.xlsb', 50 )
wb.Close()
os.remove(naam + '.xlsx') 

All my colleagues can run the script without error. Is it possible to find using Python where the file is in use? I think it is because of a setting in my os.

  • Could you make sure that excel file is not open in another program? For example, Excel itself? This has happened to me a lot as well. – Emil Mirzayev Nov 15 '21 at 06:59
  • I opened Process manager and can't find Excel in the tasks and processes. I am looking for if I can find where it is in use. – Ellis Nijland Nov 15 '21 at 07:06
  • then there is probably another script/or program which has that excel opened. If you have a shared system, it might be opened on someone else's computer as well – Emil Mirzayev Nov 15 '21 at 07:08
  • That doesn't seems to be the problem. Together with 5 colleagues we run the script on the same time. I am the only one with the problem. The problem started a month ago but I can't find out what happened. – Ellis Nijland Nov 15 '21 at 07:12
  • another problem could be your computer/user does not have permission to read that file. Could you try to opening that file manually on excel? If it does not open, then it is file reading rights for the current user. If it does open, then there is another process which has that file open somewhere in the system. Even antivirus could block the access to file – Emil Mirzayev Nov 15 '21 at 07:16
  • I can open the file. Is it possible to find out which process uses it? – Ellis Nijland Nov 15 '21 at 07:16
  • IF you are using windows, refer to this: https://stackoverflow.com/questions/379689/identify-process-using-a-file – Emil Mirzayev Nov 15 '21 at 07:21
  • Check that `str(date.today()` does not return a string with `/` in it. If it does, that is a problem because Windows filenames may not contain `/`. And because your `except` clause assumes that `os.remove()` could only possibly fail if the file is not there, you don't know if the problem was really an invalid filename. – BoarGules Nov 15 '21 at 08:10

1 Answers1

0

I have found the problem. It seems the error was caused because of my pandas version. I had 1.3.4 and when I downgraded to 1.1.1 it worked again. Thanks you all!