Why is the WindowsError while deleting the temporary file?

↘锁芯ラ 提交于 2019-12-06 00:49:03

From the documentation:

mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. New in version 2.3.

So, mkstemp returns both the OS file handle to and the filename of the temporary file. When you re-open the temp file, the original returned file handle is still open (no-one stops you from opening twice or more the same file in your program).

If you want to operate on that OS file handle as a python file object, you can:

>>> __, filename = tempfile.mkstemp()
>>> fptr= os.fdopen(__)

and then continue with your normal code.

The file is still open. Do this:

fh, filename = tempfile.mkstemp()
...
os.close(fh)
os.remove(filename)

I believe you need to release the fptr to close the file cleanly. Try setting fptr to None.

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