无法删除文件 - 文件正在被另一个进程使用

Unable to delete file - File being used by another process

我目前使用 Pillow(和 windows)库将 2 种类型的文件转换为 jpeg。问题是我创建了一个 tmp 文件来更改 (crop/re-size/rotate/etc) 但事后我无法删除它。 如果文件是X类型可以删除,如果不是X类型会报错。 两种文件类型的过程相同,但删除非 X 类型的文件时出现错误。 已经尝试强制 fout.close() 即使 "with" 语句默认执行它。

如果我设置一个try/except语句我知道它可以处理,但是文件不会被删除。

程序只有一个实例运行,files/directory中没有并发,写权限没有问题,貌似我关闭了所有的描述符。

        #If the file is X TYPE
        if is X:
            # Search for X TYPE file header and store index
            index = data.find(X_FILE_HEADER)

            # Only process file containing X otherwise return
            if index == -1:
                self.my_logger.error(
                    'Could not find X signature on file "%s", ' % inputfile)
                return
            try:
                outputfile += '.X'
                with open(outputfile, 'wb') as fout:
                    fout.write(data[index:])
            except:
                self.my_logger.critical('Could not create file "%s"' % outputfile)
                return
        # Not X file type
        else:  
            try:
                with open(outputfile, 'wb') as fout:
                    fout.write(data)
            except:
                self.my_logger.critical('Could not create file "%s"' % outputfile)
                return

        # Check if chart name in conf file
        for chart in self.chart_list:
            if os.path.basename(outputfile).startswith(chart.name):
                if isX:
                    tmp_chart_name = outputfile.replace(".x",".jpeg")
                else:
                    tmp_chart_name = outputfile.replace(".z",".jpeg")

        # Tmp for legend crop box usage
        im = tmp = PIL.Image.open(outputfile)

        # The output file wont have any timestamp
        outputfile_jpeg = os.path.join(os.path.dirname(outputfile),tmp_chart_name)

        # Check if rotation needed
        if rotation:
            im = im.rotate(float(rotation))

        # Check if crop needed
        if crop_box:
            box = tuple(map(int, crop_box.split(',')))
            im = im.crop(box)
            im.copy()

        # Check if legend crop/relocate needed
        if legend_crop_box:
            box = tuple(map(int, legend_crop_box.split(',')))
            legend_box = tmp.crop(box)
            im.paste(legend_box, (0, 0))

        # Convert the image
        im.convert('RGB').save(outputfile_jpeg)
        im.close()
        tmp.close()

        # Delete png file - Where is where the problem/bug presists
        if os.path.exists(outputfile):
           os.remove(outputfile)

我得到的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
    return self.func(*args)
  File "getmail.py", line 512, in get_email
    self.deamon.process_email()
  File "getmail.py", line 175, in process_email
    os.path.join(self.modifieddir, filename))
  File "getmail.py", line 302, in convert_file
    os.remove(outputfile)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:\FILE_TRUNCADED_PATH\my_file.x'

可能与这一行有关:

im = tmp = PIL.Image.open(outputfile)

实际上并没有打开图像的两个副本。相反,您可能想要这样的东西:

im = PIL.Image.open(outputfile)
tmp = im.copy()