![](/img/trans.png)
[英]Do I need to close the OS-level handle returned to me by tempfile.mkstemp if not using it?
[英]Python - How do I convert “an OS-level handle to an open file” to a file object?
一個元組,包含一個打開文件的操作系統級句柄(由os.open()返回)和該文件的絕對路徑名,按順序排列。
如何將操作系統級別的句柄轉換為文件對象?
要將文件描述符包裝在“文件對象”中,請使用fdopen()。
所以我嘗試過:
>>> import tempfile
>>> tup = tempfile.mkstemp()
>>> import os
>>> f = os.fdopen(tup[0])
>>> f.write('foo\n')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor
您可以使用
os.write(tup[0], "foo\n")
寫入句柄。
如果要打開用於寫入的句柄,則需要添加“w”模式
f = os.fdopen(tup[0], "w")
f.write("foo")
以下是使用with語句的方法:
from __future__ import with_statement
from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
tf.write('foo\n')
你忘了在fdopen()中指定打開模式('w')。 默認值為'r',導致write()調用失敗。
我認為mkstemp()創建的文件只供閱讀。 用'w'調用fdopen可能會重新打開它以進行寫入(您可以重新打開由mkstemp創建的文件)。
temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write('foo\n')
temp.close()
你的目標是什么? tempfile.TemporaryFile
不適合您的目的嗎?
我無法對答案發表評論,所以我將在此發表評論:
要創建用於寫訪問的臨時文件,可以使用tempfile.mkstemp並指定“w”作為最后一個參數,如:
f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
os.write(f[0], "write something")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.