我正在尝试从我的python脚本中打开文本编辑器,我注意到一些显然与我对诱饵文件文档的理解相矛盾的东西。
我的实验是从Alex的回答开始的。
我的密码-
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声明的文件对象上的delete=True,但是即使这样,我仍然能够向它写入和读取内容。我不明白为什么会这样。根据医生的说法-
如果delete为true (默认值),则文件一旦关闭即被删除。
如果调用close会删除该文件,那么我就无法写入并读取该文件。但是它会显示执行时输入的文件的正确内容。就像一个tempfile一样,文件在我打开终端并运行脚本的目录中是不可见的。更奇怪的是,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)))发布于 2018-11-11 06:53:38
让我们更深入地了解您的代码。
首先,创建临时文件。
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? : Truehttps://stackoverflow.com/questions/53246421
复制相似问题