为什么 Python 流方法不会在已删除的文件上引发异常?

问题描述 投票:0回答:1

我一直在Python中使用基于文件的流,并注意到当流的底层文件被删除时,几种方法(例如

write
close
writable
)不会引发异常(例如,每次致电
os.remove()
)。

查看了标准库文档here - 没有任何内容具体提及如果流的基础文件被删除,这些方法将如何表现 - 但我观察到的行为似乎不直观。例如,可以想象这样一种情况:应用程序认为它已成功将关键信息写入日志文件 - 但实际上日志文件已被删除,并且应用程序不知道它不再存在,因为没有引发异常.

下面是一些示例代码,说明了这种行为。我使用Python 3.10.7来执行它。

import os
from os.path import exists

p = "./myfile.txt"
f = open(p, "w")
f.write("Here is my content\n")
f.flush()
os.remove(p)
print(exists(p))  # False (as expected)
print(f.writable())  # True - but 'myfile.txt' has been deleted!
f.write("Some more content")  # Does not raise an exception!
f.flush()  # Does not raise an exception
exists(p)  # Still False - which is expected (and I confirmed there is no file at path "p")
f.close()  # Does not raise an exception!
# Line below fails with "ValueError: I/O operation on closed file."  That is consistent with the documentation for
# "close()" in the io module.
f.write("This better fail!")

如上所述,我预计一旦通过

f.write
调用删除文件,
f.flush
f.close
f.writable
os.remove()
操作会引发异常。然而,这些操作都没有引发异常。

显然,这不太可能是一个错误。但如果不是,为什么这种行为是可取的?这种行为是否特定于 Python 或整个基于文件的流?

python file stream
1个回答
0
投票

文件的读/写不是由python处理的,而是由操作系统处理的,python只是将数据放入缓冲区,操作系统负责将其写入磁盘。 (通过调用内核模式函数)

当操作系统写入不存在的文件时,操作系统会做什么取决于操作系统,例如在 Windows 上,上面的代码确实会引发错误

Traceback (most recent call last):
  File "example_python.py", line 8, in <module>
    os.remove(p)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: './myfile.txt'

Linux 不是这种情况,您可以在这个答案中阅读更多相关信息如果指向的文件被移动或删除,Linux 上打开的文件句柄会发生什么

© www.soinside.com 2019 - 2024. All rights reserved.