BytesIO object casted into TextIOWrapper does not have fileno attribute.

前端 未结 1 499
悲&欢浪女
悲&欢浪女 2021-01-20 08:46

I have the following code:

>>> import io
>>> b = io.BytesIO(b\"Hello World\")
>>> f = io.TextIOWrapper(b)
>>> f.fileno()
         


        
相关标签:
1条回答
  • 2021-01-20 09:00

    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.

    0 讨论(0)
提交回复
热议问题