gpt4 book ai didi

python:如果我使用 fdopen,需要从 mkstemp 关闭文件吗?

转载 作者:太空狗 更新时间:2023-10-29 18:04:04 24 4
gpt4 key购买 nike

以下哪项更正确?

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()

最佳答案

查看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

关于python:如果我使用 fdopen,需要从 mkstemp 关闭文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7799680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com