简体   繁体   English

Python 中的类文件对象到底是什么?

[英]What is exactly a file-like object in Python?

In http://docs.python.org/library/json.html :http://docs.python.org/library/json.html

simplejson.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, use_decimal[, **kw]]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object.将 fp(一个支持 .read() 且包含 JSON 文档的类文件对象)反序列化为 Python 对象。

I do know what read() and write() do.我确实知道read()write()做什么。

But after reading this description "read()-supporting file-like object", I find I don't know what object type supports the read() and write() .但是在阅读了这个描述“read()-supporting file-like object”之后,我发现我不知道什么对象类型支持read()write()

And I can't find that in the rest of documentation.我在其余的文档中找不到。 Anyone could elaborate more on the statement?任何人都可以详细说明该声明吗?

Why I ask this question is for getting "simplejson.load(urllib.open(...))" done.为什么我问这个问题是为了完成“simplejson.load(urllib.open(...))”。
The return value of "urllib.open(...)" is not a valid object, so I have to tailor it for simplejson. “urllib.open(...)”的返回值不是一个有效的对象,所以我必须为simplejson定制它。 However, it seems like that string is not read()-supporting.但是,似乎该字符串不支持 read()。

From the glossary :词汇表

file-like object 类文件对象

A synonym for file object文件对象的同义词

and a file object is和一个文件对象是

file object 文件对象

An object exposing a file-oriented API (with methods such as read() or write()) to an underlying resource.向底层资源公开面向文件的 API(使用 read() 或 write() 等方法)的对象。 Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.).根据创建的方式,文件对象可以调解对真实磁盘文件或其他类型的存储或通信设备(例如标准输入/输出、内存缓冲区、套接字、管道等)的访问。 . File objects are also called file-like objects or streams.文件对象也称为类文件对象或流。

There are actually three categories of file objects: raw binary files, buffered binary files and text files.实际上存在三类文件对象:原始二进制文件、缓冲二进制文件和文本文件。 Their interfaces are defined in the io module.它们的接口在 io 模块中定义。 The canonical way to create a file object is by using the open() function.创建文件对象的规范方法是使用 open() 函数。

In Python, a file object is an object exposing an API having methods for performing operations typically done on files, such as read() or write() .在 Python 中,文件对象是公开 API 的对象,该 API 具有用于执行通常对文件执行的操作的方法,例如read()write()

In the question's example: simplejson.load(fp, ...) , the object passed as fp is only required to have a read() method, callable in the same way as a read() on a file (ie accepting an optional parameter size and returning either a str or a bytes object).在问题的示例中: simplejson.load(fp, ...) ,作为fp传递的对象只需要有一个read()方法,可调用方式与文件上的read()相同(即接受可选参数size并返回strbytes对象)。

This does not need to be a real file, though, as long as it has a read() method.不过,它不需要是一个真实的文件,只要它有一个read()方法。

A file-like object is just a synonym for file-object .类似文件的对象只是file-object的同义词。 See Python Glossary .请参阅Python 词汇表

File-like objects are mainly StringIO objects, connected sockets and, well, actual file objects.类文件对象主要是StringIO对象、连接的套接字以及实际的文件对象。

If everything goes well, urllib.urlopen() returns a file-like object supporting the necessary methods.如果一切顺利, urllib.urlopen()会返回一个支持必要方法的类文件对象。

The IO Class Hierarchy section in the IO documentation contains a table listing the built-in and stub methods for the different types of file-like objects. IO 文档中的IO 类层次结构部分包含一个表格,其中列出了不同类型的类文件对象的内置方法和存根方法。

Basically, there is a hierarchy of abstract base classes:基本上,抽象基类有一个层次结构:

To implement a file-like object, you would subclass one of the three descendants of IOBase , but not IOBase itself.要实现类似文件的对象,您可以继承IOBase的三个后代之一,但不是IOBase本身。 See this answer for attempting to determine which of these a given file-like object is.请参阅此答案以尝试确定给定的类文件对象中的哪一个。

Each of these classes provides various stub methods and mixins:这些类中的每一个都提供了各种存根方法和 mixin:

Class班级 Stub Methods存根方法 Mixins混合
IOBase fileno , seek , truncate fileno号, seektruncate close , closed , __enter__ , __exit__ , flush , isatty , __iter__ , __next__ , readable , readline , readlines , seekable , tell , writable , writelines close , closed , __enter__ , __exit__ , flush , isatty , __iter__ , __next__ , readable , readline , readlines , seekable , tell , writable , writelines
RawIOBase readinto , write readintowrite read , readall read readall
BufferedIOBase detach , read , read1 , write detachreadread1write readinto , readinto1 readintoreadinto1
TextIOBase detach , read , readline , write detachreadreadlinewrite encoding , errors , newlines encoding , errors , newlines

The documentation for these methods can be found in the documentation for the classes, linked above.这些方法的文档可以在上面链接的类文档中找到。

This is the API for all file-like objects in Python (as of 3.10.5).这是 Python 中所有类文件对象的 API(从 3.10.5 开始)。

# All file-like objects inherit the IOBase interface:
# Documented at https://docs.python.org/3/library/io.html#io.IOBase .
    close() -> None
    closed() -> bool # Implemented as @property `closed`
    fileno() -> int
    flush() -> None
    isatty() -> bool
    readable() -> bool
    readline(size: int = -1) -> Union[str, bytes]
    readlines(hint: Union[int, None] = None) -> list
    seek(pos: int, whence: int = io.SEEK_SET) -> int # SEEK_SET is 0
    seekable() -> bool
    tell() -> int
    truncate(pos: int = None) -> int # The parameter is named "size" in class FileIO
    writable() -> bool
    writelines(lines: list) -> None
    __del__() -> None
# Documented at https://docs.python.org/3/library/io.html#class-hierarchy .
    __enter__()
    __exit__(*args) -> None:
    __iter__()
    __next__() -> Union[str, bytes]
# Documented in paragraph at https://docs.python.org/3/library/io.html#io.IOBase .
# Note that while the documentation claims that the method signatures 
# of `read` and `write` vary, all file-like objects included in the Python 
# Standard Library have the following exact method signatures for `read` and `write`:
    read(size: int = -1) -> Union[str, bytes]
    write(b: Union[str, bytes]) -> int # The parameter is named "s" in TextIOBase

Specific file-like objects may implement more than this, but this is the subset of methods that are common to ALL file-like objects.特定的类文件对象可能实现的不止于此,但这是所有类文件对象共有的方法的子集。

simplejson has the calls loads and dumps that consumes and produce strings instead of file like objects. simplejson 的调用加载转储消耗和生成字符串,而不是像文件这样的对象。

This link has an example in the context of StringIO and simplejson for both file-like and string objects.此链接在 StringIO 和 simplejson 的上下文中为类文件和字符串对象提供了一个示例。

http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.3/docs/index.html http://svn.red-bean.com/bob/simplejson/tags/simplejson-1.3/docs/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM