Temporary file with specific file extension in Python 3

对着背影说爱祢 提交于 2019-12-03 23:58:53

问题


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.

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.

How can I create a temporary file while specifying the extension (or the entire name), using the tempfile module?

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.


回答1:


This doesn't work for you?

In [2]: tempfile.NamedTemporaryFile(suffix='.tif').name
Out[2]: '/var/folders/gq/swc6jtld5853skyq_xc2lpc40000gn/T/tmplrtwvxg7.tif'


来源:https://stackoverflow.com/questions/38900216/temporary-file-with-specific-file-extension-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!