0

I try to integrate an external C# Library in a Python project. The library reads and converts some file contents that I want to consume in Python and then delete the file:

import clr
from pathlib import Path
import os
import gc

my_dll = Path('C:/MyLib') #path without .dll suffix
clr.AddReference(str(my_dll))
from MyLib import MyFileReader

file = Path('C:/myfile.txt')

reader = MyFileReader()
result = reader.Initialize(str(file))
# do something with result

del reader
clr.System.GC.Collect()
gc.collect()
os.remove(str(file)) # WinError 32 The process cannot access the file because another process has locked a portion of the file.

MyFileReader properly reads and returns the file contents, but I'm not able to delete the file with os.remove as the reader is not properly garbage collected and still holds a lock on the file. I assume the authors of the external library didn't implement the closing of the file, but I cannot check as I don't have access to the source code of the external library. How can I properly remove MyFileReader from memory?

user106745
  • 183
  • 1
  • 8

0 Answers0