擅长:python、mysql、java
<p>这不太简洁,我想可能存在异常安全问题(例如,如果“original_path”不存在,或者当您打开文件时临时的_copy对象超出范围,会发生什么情况),但是这段代码会为清理添加一点RAII。这里直接使用NamedTemporaryFile的不同之处在于,您最终得到的不是一个file对象,而是一个偶尔需要的文件(例如,如果您计划调用其他代码来读取它,或者类似的文件)</p>
<pre><code>import os,shutil,tempfile
class temporary_copy(object):
def __init__(self,original_path):
self.original_path = original_path
def __enter__(self):
temp_dir = tempfile.gettempdir()
base_path = os.path.basename(self.original_path)
self.path = os.path.join(temp_dir,base_path)
shutil.copy2(self.original_path, self.path)
return self.path
def __exit__(self,exc_type, exc_val, exc_tb):
os.remove(self.path)
</code></pre>
<p>在你的代码中你会写:</p>
<pre><code>with temporary_copy(path) as temporary_path_to_copy:
... do stuff with temporary_path_to_copy ...
# Here in the code, the copy should now have been deleted.
</code></pre>