Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BytesIO object casted into TextIOWrapper does not have fileno attribute.

Tags:

python

io

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?

like image 803
Alex Avatar asked Oct 29 '22 10:10

Alex


1 Answers

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:

  • Open a file for read+write
  • Write your string
  • Rewind the file to the beginning

There must be a better design, however, that won't force you to use this workaround.

like image 176
slezica Avatar answered Nov 12 '22 19:11

slezica