Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the tempfile.mkstemp(text=...) parameter actually do?

Tags:

python

Is the text=True|False parameter in mkstemp something Windows specific? I'm sorry that I have to ask, but I'm a UNIX/Linux person.

At the low level of file descriptors - where the mkstemp operates - are all files just bytes. I was surprised to see the text= parameter. The only hint I found is a comment in os.open docs:

In particular, on Windows adding O_BINARY is needed to open files in binary mode.


For completness the tempfile.mkstemp docs:

If text is specified and true, the file is opened in text mode. Otherwise, (the default) the file is opened in binary mode.

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.

And an example. It indeed returns a file descriptor and a filename:

>>> import tempfile
>>> tempfile.mkstemp(text=False)
(3, '/tmp/tmp9z8rp2_2')
>>> tempfile.mkstemp(text=True)
(4, '/tmp/tmpc6z9j2yu')
like image 355
VPfB Avatar asked Dec 27 '25 14:12

VPfB


1 Answers

os.open on Windows treats O_BINARY flags differently than if you don't specify it.

The end of line conversion is done as OS level by Windows (open is provided by Windows as a POSIX emulation layer) unless O_BINARY is set.

On Linux this has no effect, but it may be needed for portability purposes.

So the answer is: the text parameter makes sure that underlying open is called without O_BINARY.

like image 69
Jean-François Fabre Avatar answered Dec 30 '25 04:12

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!