我正在尝试从 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/