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.
import os, shutil, tempfile
def create_temporary_copy(src):
# create the temporary file in read/write mode (r+)
tf = tempfile.TemporaryFile(mode='r+b', prefix='__', suffix='.tmp')
# on windows, we can't open the the file again, either manually
# or indirectly via shutil.copy2, but we *can* copy
# the file directly using file-like objects, which is what
# TemporaryFile returns to us.
# Use `with open` here to automatically close the source file
with open(src,'r+b') as f:
shutil.copyfileobj(f,tf)
# display the name of the temporary file for diagnostic purposes
print 'temp file:',tf.name
# rewind the temporary file, otherwise things will go
# tragically wrong on Windows
tf.seek(0)
return tf
# make a temporary copy of the file 'foo.txt'
name = None
with create_temporary_copy('foo.txt') as temp:
name = temp.name
# prove that it exists
print 'exists', os.path.isfile(name) # prints True
# read all lines from the file
i = 0
for line in temp:
print i,line.strip()
i += 1
# temp.close() is implicit using `with`
# prove that it has been deleted
print 'exists', os.path.isfile(name) # prints False
没有一个是直接的,但是可以使用
tempfile
和shutil.copy2
的组合来实现相同的结果:不过,您需要处理删除调用者中的临时文件。
这不太简洁,我想可能存在异常安全问题(例如,如果“original_path”不存在,或者当您打开文件时临时的_copy对象超出范围,会发生什么情况),但是这段代码会为清理添加一点RAII。这里直接使用NamedTemporaryFile的不同之处在于,您最终得到的不是一个file对象,而是一个偶尔需要的文件(例如,如果您计划调用其他代码来读取它,或者类似的文件)
在你的代码中你会写:
对@tramdas的回答的一种变体,解释了在windows上文件不能打开两次的事实。此版本忽略文件扩展名的保留。
相关问题 更多 >
编程相关推荐