python - 为什么即使在关闭临时文件后我仍然可以写入和读取它?

标签 python python-3.x subprocess temporary-files nano

我正在尝试从 python 脚本中打开文本编辑器,我注意到一些内容显然与我对 tempfile 文档的理解相矛盾。 .

我的实验从 Alex Martelli 的 answer 开始。 .
我的代码 -

import os
import tempfile
import subprocess

f = tempfile.NamedTemporaryFile(mode='w+t', delete=True)
n = f.name
print('Does exist? : {0}'.format(os.path.exists(n)))
f.close()
print('Does exist? : {0}'.format(os.path.exists(n)))

subprocess.run(['nano', n])
with open(n) as f:
    print (f.read())

print('Does exist? : {0}'.format(os.path.exists(n)))

输出:

Does exist? : True
Does exist? : False
Hello from temp file.

Does exist? : True

在代码中,我在使用 delete=True 声明的文件对象上显式调用 close,但即使如此,我也可以向其中写入和读取内容。我不明白为什么会发生这种情况。 根据文档-

If delete is true (the default), the file is deleted as soon as it is closed.

如果调用close删除该文件,那么我不应该能够写入然后读取它。但它会在 nano 执行时显示您输入的文件的正确内容。与临时文件一样,该文件在我打开终端并运行脚本的目录中不可见。 更奇怪的是,前两次os.path.exists工作正常,第三次可能不正确
我在这里错过了什么吗?

额外实验:
如果我运行以下代码,那么我可以清楚地看到创建的文件。但原始代码中并没有发生这种情况。

n = '.temp'
subprocess.run(['nano', n])
with open(n) as f:
    print (f.read())

print('Does exist? : {0}'.format(os.path.exists(n)))

最佳答案

让我们更深入地了解您的代码。

首先创建临时文件

f = tempfile.NamedTemporaryFile(mode='w+t', delete=True)
n = f.name
print('Does exist? : {0}'.format(os.path.exists(n)))

和这个输出

Does exist? : True

所以没有什么可担心的。然后在接下来的语句中

f.close()
print('Does exist? : {0}'.format(os.path.exists(n)))

您正在关闭文件,实际上该文件被删除,因为您得到以下输出:

Does exist? : False

之后,您将通过以下方式重新创建文件

subprocess.run(['nano', n])
with open(n) as f:
    print (f.read())

这就是为什么之后的命令

print('Does exist? : {0}'.format(os.path.exists(n)))

返回

Does exist? : True

关于python - 为什么即使在关闭临时文件后我仍然可以写入和读取它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53246421/

相关文章:

python - Pandas 更新后无效的转义序列

python - 如何替换字符串中的数字?

python3 计数器还对滑动窗口中的索引位置进行平均

python - PyCarl 的 cmake 构建过程失败,并要求使用 -fPIC 重新编译

python - 在 subprocess.Popen 命令中使用变量

python - 覆盖 OPTION 请求的 Django Rest Framework header

python - 无法在 Python 中的 gzip 文件中执行基于正则表达式的操作

python-3.x - python 计算元组中的出现次数

python - finplot 作为布局中的小部件

python-2.7 - 使用 Request、HttpNtlmAuth 进行带认证的系统调用