下面哪一项更正确?
fi, path = tempfile.mkstemp()
f = os.fdopen(fi, "w")
f.write(res)
f.close()
os.close(fi)或者:
fi, path = tempfile.mkstemp()
f = os.fdopen(fi, "w")
f.write(res)
f.close()发布于 2011-10-18 05:38:15
检查f.fileno(),应该和fi一样。您应该只关闭该文件描述符一次,因此第二次是正确的。
在Unix上,第一个错误会导致错误:
>>> f.close()
>>> os.close(fi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 9] Bad file descriptor发布于 2011-10-18 05:48:13
如果在足够新的Python上,您可以使用以下代码:
with os.fdopen(tempfile.mkstemp()[0]) as f:
f.write(res)发布于 2013-07-21 05:43:38
如果您需要路径,请继续跟进最新的答案:
f_handle, f_path = tempfile.mkstemp()
with os.fdopen(f_handle, 'w') as f:
f.write(res)
try:
# Use path somehow
some_function(f_path)
finally:
# Clean up
os.unlink(f_path)https://stackoverflow.com/questions/7799680
复制相似问题