在打开包含目录的文件后安全删除目录吗?

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

我有一些代码需要返回文件对象并清理包含的目录,例如:

def create_file():
    # create a temp directory: temp_dir
    # generate a file inside the directory: filename

    file_obj = open(filename, 'rb')
    shutil.rmtree(temp_dir)
    return file_obj

如果我有文件句柄(open()的结果,可以安全地删除包含目录吗?

python python-3.x file directory delete-file
1个回答
1
投票

取决于您如何定义“安全”。在Linux机器上:

>>> p = os.path.join(os.getcwd(), "tmpdir")
>>> def foo(p):
...     os.makedirs(p)
...     f = open(os.path.join(p, "tmp.txt"), "w")
...     shutil.rmtree(p)
...     return f
... 
>>> f = foo(p)
>>> f
<open file '/home/bruno/tmpdir/tmp.txt', mode 'w' at 0x7f14f65c2270>
>>> f.write("foo")
>>> f.close()
>>> f.name
'/home/bruno/tmpdir/tmp.txt'
>>> open(f.name).read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '/home/bruno/tmpdir/tmp.txt'
>>> 
>>> os.listdir(p)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: '/home/bruno/tmpdir'
© www.soinside.com 2019 - 2024. All rights reserved.