I have the following code:
>>> import io
>>> b = io.BytesIO(b"Hello World")
>>> f = io.TextIOWrapper(b)
>>> f.fileno()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
io.UnsupportedOperation: fileno
However, when I load a file in, there is a fileno
attribute:
>>> f = open("test.py")
>>> f.fileno()
3
Is there a way to create a fileno
attribute for the first case, where I am casting a BytesIO
object to the TextIOWrapper
object?
Well, fileno
is not available because there is no file.
The fileno()
method returns an integer, representing the position of an open file in the operating system's table of process-related files. If you don't actually open a file, the operating system won't give you a file number.
Your program's standard input, output and error streams (those you read with input
and write with print
) are numbered 0
, 1
and 2
. Subsequent open files are usually given sequential numbers by the system.
This cannot be faked reliably: anything you return from fileno()
when no actual file is backing the object is a lie. This is why the implementation chose to raise UnsupportedOperation
. No return makes sense, except perhaps None
.
If it's absolutely imperative that you have a fileno()
for your string content, you could do this:
read+write
There must be a better design, however, that won't force you to use this workaround.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With