Python 3中具有特定文件扩展名的临时文件 [英] Temporary file with specific file extension in Python 3
问题描述
我正在为一段代码编写一些单元测试,这些代码需要一个路径,如果文件具有已知扩展名,则尝试加载该文件,然后进行更仔细的检查.
I am writing some unit tests for a piece of code that takes a path and attempts to load the file if it has a known extension, then does more careful checking.
在单元测试中,我想创建一个具有正确扩展名但内容不正确的临时文件,在我的情况下,我将创建一个空文件,并伪装为test.tif
.
In the unit test, I would like to create a temporary file that has the correct extension, but incorrect contents, in my case an empty file posing as test.tif
.
如何使用tempfile
模块在指定扩展名(或全名)的同时创建一个临时文件?
How can I create a temporary file while specifying the extension (or the entire name), using the tempfile
module?
我已经看过NamedTemporaryFile
类以及suffix
和prefix
参数,但是我仍然无法设置扩展名.我想我可以在一个临时目录中手动创建一个文件,但是随后我就失去了自我删除功能.
I have looked at the NamedTemporaryFile
class, as well as the suffix
and prefix
parameters, but I still cannot set the extension. I suppose I could manually create a file in a temporary directory, but then I loose the self-deleting capability that I am after.
推荐答案
这对您不起作用?
In [2]: tempfile.NamedTemporaryFile(suffix='.tif').name
Out[2]: '/var/folders/gq/swc6jtld5853skyq_xc2lpc40000gn/T/tmplrtwvxg7.tif'
这篇关于Python 3中具有特定文件扩展名的临时文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!