Python - 如何将“操作系统级句柄到打开的文件”转换为文件对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/168559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - How do I convert "an OS-level handle to an open file" to a file object?
提问by Daryl Spitzer
tempfile.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.
一个元组,包含一个打开文件的操作系统级句柄(由 os.open() 返回)和该文件的绝对路径名,按顺序排列。
How do I convert that OS-level handle to a file object?
如何将该操作系统级句柄转换为文件对象?
The documentation for os.open()states:
To wrap a file descriptor in a "file object", use fdopen().
要将文件描述符包装在“文件对象”中,请使用 fdopen()。
So I tried:
所以我试过:
>>> 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
采纳答案by Peter Hoffmann
You can use
您可以使用
os.write(tup[0], "foo\n")
to write to the handle.
写入句柄。
If you want to open the handle for writing you need to add the "w"mode
如果要打开句柄进行写入需要添加“w”模式
f = os.fdopen(tup[0], "w")
f.write("foo")
回答by Daryl Spitzer
Here's how to do it using a with statement:
以下是使用 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')
回答by efotinis
You forgot to specify the open mode ('w') in fdopen(). The default is 'r', causing the write() call to fail.
您忘记在 fdopen() 中指定打开模式 ('w')。默认值为 'r',导致 write() 调用失败。
I think mkstemp() creates the file for reading only. Calling fdopen with 'w' probably reopens it for writing (you canreopen the file created by mkstemp).
我认为 mkstemp() 创建的文件仅供阅读。使用 'w' 调用 fdopen 可能会重新打开它以进行写入(您可以重新打开由 mkstemp 创建的文件)。
回答by hoju
temp = tempfile.NamedTemporaryFile(delete=False)
temp.file.write('foo\n')
temp.close()
回答by Alex Coventry
What's your goal, here? Is tempfile.TemporaryFile
inappropriate for your purposes?
你的目标是什么,在这里?是tempfile.TemporaryFile
不适合你的目的是什么?
回答by MartinD
I can't comment on the answers, so I will post my comment here:
我无法对答案发表评论,因此我将在此处发表评论:
To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:
要创建用于写访问的临时文件,您可以使用 tempfile.mkstemp 并指定“w”作为最后一个参数,例如:
f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
os.write(f[0], "write something")