[New-bugs-announce] [issue25202] with-statement doesn't release file handle after exception

Lauri Kajan report at bugs.python.org
Mon Sep 21 15:17:04 CEST 2015


New submission from Lauri Kajan:

Hi all,

I found out that handle to a file opened with with-statement is not released in all cases.

I'm trying to delete a file when space on a disk is filled (0 bit left) by writing this file. I catch the IOError 28 to figure this out.
I write the file within the with-statement that is wrapped with try except. In the except block I try to delete the file but the handle to the file is not released.

In the following code fill-file can't be deleted because the file is still open.
I have described the problem also in stackoverflow [1].

# I recommend filling the disk almost full with some better tool.
import os
import errno

fill = 'J:/fill.txt'
try:
    with open(fill, 'wb') as f:
        while True:
            n = f.write(b"\0")
except IOError as e:
    if e.errno == errno.ENOSPC:
        os.remove(fill)

This gives the following traceback:

Traceback (most recent call last):
  File "nospacelef.py", line 8, in <module>
    n = f.write(b"\0")
IOError: [Errno 28] No space left on device

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "nospacelef.py", line 8, in <module>
    n = f.write(b"\0")
IOError: [Errno 28] No space left on device

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "nospacelef.py", line 11, in <module>
    os.remove(fill)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'J:/fill.txt'



[1] http://stackoverflow.com/questions/32690018/cant-delete-a-file-after-no-space-left-on-device

----------
components: IO
messages: 251225
nosy: Lauri Kajan
priority: normal
severity: normal
status: open
title: with-statement doesn't release file handle after exception
type: behavior
versions: Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue25202>
_______________________________________


More information about the New-bugs-announce mailing list