问题描述
我有以下代码:
>>> 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
然而,当我加载文件时,有一个 fileno
属性:
However, when I load a file in, there is a fileno
attribute:
>>> f = open("test.py")
>>> f.fileno()
3
有没有办法创建 fileno
第一种情况的属性,我将 BytesIO
对象转换为 TextIOWrapper
对象?
Is there a way to create a fileno
attribute for the first case, where I am casting a BytesIO
object to the TextIOWrapper
object?
推荐答案
那么, fileno
不可用,因为没有文件。
fileno()
方法返回一个整数,表示操作系统的进程相关文件表中的打开文件的位置。如果你没有实际打开文件,操作系统将不会给你一个文件号。
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.
你的程序的标准输入,输出和错误流(您使用输入
读取并使用 print
编写的那些)的编号为 0
, 1
和 2
。后续打开的文件通常由系统给出序列号。
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.
这不能可靠地伪造:从 fileno()当没有实际文件支持时,对象就是谎言。这就是实现选择提高
UnsupportedOperation
的原因。没有任何回报是有意义的,除非无
。
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
.
如果您必须拥有
fileno()
对于你的字符串内容,你可以这样做:
If it's absolutely imperative that you have a
fileno()
for your string content, you could do this:
打开<$ c的文件$ c>读+写
- 写你的字符串
- 将文件倒回到开头
但必须有更好的设计,不会强迫您使用此解决方法。
There must be a better design, however, that won't force you to use this workaround.
这篇关于转换为TextIOWrapper的BytesIO对象没有fileno属性。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!