我有一些代码需要返回文件对象并清理包含的目录,例如:
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()
的结果,可以安全地删除包含目录吗?
取决于您如何定义“安全”。在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'