我知道可以创建一个临时文件,并将要复制的文件的数据写入其中.我只是想知道是否有这样的功能:
create_temporary_copy(file_path)
Run Code Online (Sandbox Code Playgroud)
Tor*_*ler 22
没有一个直接的,但你可以使用的组合tempfile
并shutil.copy2
达到相同的结果:
import tempfile, shutil, os
def create_temporary_copy(path):
temp_dir = tempfile.gettempdir()
temp_path = os.path.join(temp_dir, 'temp_file_name')
shutil.copy2(path, temp_path)
return temp_path
Run Code Online (Sandbox Code Playgroud)
但是,您需要处理删除调用方中的临时文件.
以下比所选答案更简洁(OP 的要求)。享受!
import tempfile, shutil, os
def create_temporary_copy(path):
tmp = tempfile.NamedTemporaryFile(delete=True)
shutil.copy2(path, tmp.name)
return tmp.name
Run Code Online (Sandbox Code Playgroud)
这不是那么简洁,我想可能存在异常安全问题(例如,如果'original_path'不存在会发生什么,或者当文件打开时,temporary_copy对象超出范围)但是此代码添加一点RAII清理.直接使用NamedTemporaryFile的不同之处在于,不是以文件对象结束,而是最终得到一个文件,这偶尔也是可取的(例如,如果您打算调用其他代码来读取它,或者其他一些文件.)
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)
Run Code Online (Sandbox Code Playgroud)
在你的代码中你写的:
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.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11985 次 |
最近记录: |