设备空间已满后无法删除文件

3

我正在将一堆文件写入几个硬盘中。所有的文件都无法放在一个硬盘上,因此如果第一个硬盘空间不足,我就把它们写到下一个硬盘上。我使用IOError 28捕获异常来判断这种情况。

我的确切问题是:当我试图删除最后一个写入第一个硬盘的文件(不完整的文件)时,我得到了一个新的异常,我并不完全理解。似乎with块无法关闭文件,因为磁盘上没有剩余空间。

我正在使用Windows系统,并且硬盘格式化为NTFS格式。

请问有人能帮忙吗?

# Here's a sample code
# I recommend first to fill a disk to almost full with a large dummy file.
# On windows you could create a dummy file with
#   'fsutil file createnew large.txt 1000067000000'

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)

以下是追溯信息:

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'

3
我认为这个错误“WindowsError: [Error 32] The process cannot access the file because it is being used by another process”已经很清楚地指明了原因。 - ρss
2
@ρss 我不是很清楚。如果文件正在写入(在Windows上),它如何被另一个进程使用?如果这个“另一个进程”实际上是同一个进程,那么问题就是为什么“with”语句未能正确关闭文件。文件对象的上下文管理器保证文件将被关闭,并释放操作系统级别的资源,即使发生异常也是如此。 - user4815162342
1
如果按照这里呈现的方式运行代码,with 语句应该确保在删除文件之前关闭它。 - user4815162342
@user4815162342,这正是问题所在。with语句无法关闭文件。似乎当它尝试时,会引发另一个IOError:[Errno 28]。我尝试使用传统的f = open(fill,'wb')逻辑,并在except块中删除之前关闭f,然后f.close()引发了相同的IOError。 - LauriK
J 是网络驱动器还是本地驱动器?尝试调查正在处理您的文件的进程,以确定它是相同的进程还是不同的进程。https://superuser.com/questions/845971/how-do-i-find-out-what-files-a-process-is-writing-to - ρss
显示剩余5条评论
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接