io
— Core tools for working with streams用于处理流的核心工具¶
Source code: Lib/io.py
Overview概述¶
The io
module provides Python’s main facilities for dealing with various types of I/O. io
模块提供Python处理各种类型I/O的主要工具。There are three main types of I/O: text I/O, binary I/O and raw I/O. 有三种主要类型的I/O:文本I/O、二进制I/O和原始I/O。These are generic categories, and various backing stores can be used for each of them. 这些是通用类别,可以为每个类别使用各种后备存储。A concrete object belonging to any of these categories is called a file object. 属于这些类别中任何一个的具体对象称为文件对象。Other common terms are stream and file-like object.其他常用术语是流和类文件对象。
Independent of its category, each concrete stream object will also have various capabilities: it can be read-only, write-only, or read-write. 独立于其类别,每个具体流对象还将具有各种功能:它可以是只读、只读或读写。It can also allow arbitrary random access (seeking forwards or backwards to any location), or only sequential access (for example in the case of a socket or pipe).它还可以允许任意随机访问(向前或向后搜索任何位置),或仅允许顺序访问(例如,在插座或管道的情况下)。
All streams are careful about the type of data you give to them. 所有流都会仔细考虑您提供给它们的数据类型。For example giving a 例如,将str
object to the write()
method of a binary stream will raise a TypeError
. str
对象赋予二进制流的write()
方法将引发TypeError
。So will giving a 为文本流的bytes
object to the write()
method of a text stream.write()
方法提供bytes
对象也是如此。
Changed in version 3.3:版本3.3中更改: Operations that used to raise 用于引发IOError
now raise OSError
, since IOError
is now an alias of OSError
.IOError
的操作现在会引发OSError
,因为IOError
现在是OSError
的别名。
Text I/O文本I/O¶
Text I/O expects and produces 文本输入/输出需要并生成str
objects. str
对象。This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.这意味着,无论何时备份存储本机由字节组成(例如在文件的情况下),数据的编码和解码都是透明的,并且可以选择转换特定于平台的换行符。
The easiest way to create a text stream is with 创建文本流的最简单方法是使用open()
, optionally specifying an encoding:open()
,可以选择指定编码:
f = open("myfile.txt", "r", encoding="utf-8")
In-memory text streams are also available as 内存中的文本流也可用作StringIO
objects:StringIO
对象:
f = io.StringIO("some initial text data")
The text stream API is described in detail in the documentation of TextIOBase
.TextIOBase
文档中详细描述了文本流API。
Binary I/O二进制I/O¶
Binary I/O (also called buffered I/O) expects bytes-like objects and produces 二进制I/O(也称为缓冲I/O)需要类似字节的对象,并生成字节对象。bytes
objects. No encoding, decoding, or newline translation is performed. 不执行编码、解码或换行翻译。This category of streams can be used for all kinds of non-text data, and also when manual control over the handling of text data is desired.此类流可用于所有类型的非文本数据,也可用于需要手动控制文本数据处理的情况。
The easiest way to create a binary stream is with 创建二进制流的最简单方法是在模式字符串中使用open()
with 'b'
in the mode string:open()
和'b'
:
f = open("myfile.jpg", "rb")
In-memory binary streams are also available as 内存中的二进制流也可用作BytesIO
objects:BytesIO
对象:
f = io.BytesIO(b"some initial binary data: \x00\x01")
The binary stream API is described in detail in the docs of BufferedIOBase
.BufferedIOBase
的文档中详细描述了二进制流API。
Other library modules may provide additional ways to create text or binary streams. 其他库模块可以提供创建文本或二进制流的其他方法。See 例如,请参阅socket.socket.makefile()
for example.socket.socket.makefile()
。
Raw 原始I/O¶
Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text streams; it is rarely useful to directly manipulate a raw stream from user code. 原始I/O(也称为无缓冲I/O)通常用作二进制和文本流的低级构建块;直接从用户代码操作原始流很少有用。Nevertheless, you can create a raw stream by opening a file in binary mode with buffering disabled:不过,您可以通过在禁用缓冲的情况下以二进制模式打开文件来创建原始流:
f = open("myfile.jpg", "rb", buffering=0)
The raw stream API is described in detail in the docs of RawIOBase
.RawIOBase
的文档中详细描述了原始流API。
Text Encoding文本编码¶
The default encoding of TextIOWrapper
and open()
is locale-specific (locale.getpreferredencoding(False)
).TextIOWrapper
和open()
的默认编码是特定于语言环境的(locale.getpreferredencoding(False)
)。
However, many developers forget to specify the encoding when opening text files encoded in UTF-8 (e.g. JSON, TOML, Markdown, etc…) since most Unix platforms use UTF-8 locale by default. 然而,许多开发人员在打开以UTF-8编码的文本文件(例如JSON、TOML、Markdown等)时忘记了指定编码,因为大多数Unix平台默认使用UTF-8语言环境。This causes bugs because the locale encoding is not UTF-8 for most Windows users. 这会导致错误,因为对于大多数Windows用户来说,区域设置编码不是UTF-8。For example:例如:
# May not work on Windows when non-ASCII characters in the file.
with open("README.md") as f:
long_description = f.read()
Additionally, while there is no concrete plan as of yet, Python may change the default text file encoding to UTF-8 in the future.此外,虽然目前还没有具体的计划,但Python将来可能会将默认的文本文件编码更改为UTF-8。
Accordingly, it is highly recommended that you specify the encoding explicitly when opening text files. 因此,强烈建议您在打开文本文件时明确指定编码。If you want to use UTF-8, pass 如果要使用UTF-8,请传递encoding="utf-8"
. encoding="utf-8"
。To use the current locale encoding, 要使用当前的语言环境编码,Python 3.10中支持encoding="locale"
is supported in Python 3.10.encoding="locale"
。
When you need to run existing code on Windows that attempts to open UTF-8 files using the default locale encoding, you can enable the UTF-8 mode. 当您需要在尝试使用默认区域设置编码打开UTF-8文件的Windows上运行现有代码时,可以启用UTF-8模式。See UTF-8 mode on Windows.请参阅Windows上的UTF-8模式。
Opt-in EncodingWarning选择加入编码警告¶
To find where the default locale encoding is used, you can enable the 要查找使用默认语言环境编码的位置,可以启用-X warn_default_encoding
command line option or set the PYTHONWARNDEFAULTENCODING
environment variable, which will emit an EncodingWarning
when the default encoding is used.-X warn_default_encoding
命令行选项或设置PYTHONWARNDEFAULTENCODING
环境变量,该变量将在使用默认编码时发出EncodingWarning
。
If you are providing an API that uses 如果提供的API使用open()
or TextIOWrapper
and passes encoding=None
as a parameter, you can use text_encoding()
so that callers of the API will emit an EncodingWarning
if they don’t pass an encoding
. open()
或TextIOWrapper
并将encoding=None
作为参数传递,则可以使用text_encoding()
,以便API的调用方在不传递encoding
时发出EncodingWarning
。However, please consider using UTF-8 by default (i.e. 但是,请考虑对新API默认使用UTF-8(即encoding="utf-8"
) for new APIs.encoding="utf-8"
)。
High-level Module Interface高级模块接口¶
-
io.
DEFAULT_BUFFER_SIZE
¶ An int containing the default buffer size used by the module’s buffered I/O classes.一个int,包含模块缓冲输入/输出类使用的默认缓冲区大小。open()
uses the file’s blksize (as obtained by如果可能,请使用文件的blksize(由os.stat()
) if possible.os.stat()
获取)。
-
io.
open
(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)¶ This is an alias for the builtin这是内置open()
function.open()
函数的别名。This function raises an auditing event此函数引发一个打开的审核事件,其中包含参数open
with argumentspath
,mode
andflags
.path
、mode
和flags
。Themode
andflags
arguments may have been modified or inferred from the original call.mode
和flags
参数可能已从原始调用中修改或推断。
-
io.
open_code
(path)¶ Opens the provided file with mode以'rb'
.'rb'
模式打开提供的文件。This function should be used when the intent is to treat the contents as executable code.当目的是将内容视为可执行代码时,应使用此函数。path
should be astr
and an absolute path.path
应该是str
和绝对路径。The behavior of this function may be overridden by an earlier call to the此函数的行为可能会被之前对PyFile_SetOpenCodeHook()
.PyFile_SetOpenCodeHook()
的调用所覆盖。However, assuming that但是,假设path
is astr
and an absolute path,open_code(path)
should always behave the same asopen(path, 'rb')
.path
是str
和绝对路径,open_code(path)
的行为应始终与open(path, 'rb')
相同。Overriding the behavior is intended for additional validation or preprocessing of the file.重写行为是为了对文件进行额外的验证或预处理。New in version 3.8.版本3.8中新增。
-
io.
text_encoding
(encoding, stacklevel=2, /)¶ This is a helper function for callables that use这是一个辅助函数,用于使用open()
orTextIOWrapper
and have anencoding=None
parameter.open()
或TextIOWrapper
并具有encoding=None
参数的可调用函数。This function returns encoding if it is not如果不是None
and"locale"
if encoding isNone
.None
,则此函数返回encoding;如果encoding是None
,则返回"locale"
。This function emits an如果EncodingWarning
ifsys.flags.warn_default_encoding
is true and encoding is None.sys.flags.warn_default_encoding
为true
而encoding为None
,此函数将发出EncodingWarning
。stacklevelspecifies where the warning is emitted.指定发出警告的位置。For example:例如:def read_text(path, encoding=None):
encoding = io.text_encoding(encoding) # stacklevel=2
with open(path, encoding) as f:
return f.read()In this example, an在本例中,将为EncodingWarning
is emitted for the caller ofread_text()
.read_text()
的调用方发出EncodingWarning
。See Text Encoding for more information.有关详细信息,请参阅文本编码。New in version 3.10.版本3.10中新增。
-
exception
io.
BlockingIOError
¶ This is a compatibility alias for the builtin这是内置BlockingIOError
exception.BlockingIOError
异常的兼容性别名。
-
exception
io.
UnsupportedOperation
¶ An exception inheriting继承OSError
andValueError
that is raised when an unsupported operation is called on a stream.OSError
和ValueError
的异常,在流上调用不受支持的操作时引发该异常。
See also
sys
contains the standard IO streams:包含标准IO流:sys.stdin
,sys.stdout
, andsys.stderr
.sys.stdin
、sys.stdout
和sys.stderr
。
Class hierarchy类层次结构¶
The implementation of I/O streams is organized as a hierarchy of classes. I/O流的实现被组织为类的层次结构。First abstract base classes (ABCs), which are used to specify the various categories of streams, then concrete classes providing the standard stream implementations.首先是抽象基类(ABC),用于指定各种类型的流,然后是提供标准流实现的具体类。
Note
The abstract base classes also provide default implementations of some methods in order to help implementation of concrete stream classes.抽象基类还提供一些方法的默认实现,以帮助实现具体的流类。For example,例如,BufferedIOBase
provides unoptimized implementations ofreadinto()
andreadline()
.BufferedIOBase
提供了readinto()
和readline()
的未优化实现。
At the top of the I/O hierarchy is the abstract base class 在I/O层次结构的顶部是抽象基类IOBase
. IOBase
。It defines the basic interface to a stream. 它定义了流的基本接口。Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise 然而,请注意,对流的读写之间没有分离;如果实现不支持给定的操作,则允许它们引发UnsupportedOperation
if they do not support a given operation.UnsupportedOperation
。
The RawIOBase
ABC extends IOBase
. RawIOBase
抽象基类扩展了IOBase
。It deals with the reading and writing of bytes to a stream. 它处理字节对流的读写。FileIO
subclasses 子类RawIOBase
to provide an interface to files in the machine’s file system.为计算机文件系统中的文件提供接口。
The BufferedIOBase
ABC extends IOBase
. BufferedIOBase
抽象基类扩展了IOBase
。It deals with buffering on a raw binary stream (它处理原始二进制流(RawIOBase
). RawIOBase
)上的缓冲。Its subclasses, 其子类BufferedWriter
, BufferedReader
, and BufferedRWPair
buffer raw binary streams that are readable, writable, and both readable and writable, respectively. BufferedWriter
、BufferedReader
和BufferedRWPair
分别缓冲可读、可写以及可读写的原始二进制流。BufferedRandom
provides a buffered interface to seekable streams. 为可查找的流提供缓冲接口。Another 另一个BufferedIOBase
subclass, BytesIO
, is a stream of in-memory bytes.BufferedIOBase
子类BytesIO
是内存字节流。
The TextIOBase
ABC extends IOBase
. TextIOBase
抽象基类扩展了IOBase
。It deals with streams whose bytes represent text, and handles encoding and decoding to and from strings. 它处理字节表示文本的流,并处理字符串之间的编码和解码。TextIOWrapper
, which extends TextIOBase
, is a buffered text interface to a buffered raw stream (BufferedIOBase
). TextIOWrapper
是TextIOBase
的扩展,是缓冲原始流(BufferedIOBase
)的缓冲文本接口。Finally, 最后,StringIO
is an in-memory stream for text.StringIO
是一个内存中的文本流。
Argument names are not part of the specification, and only the arguments of 参数名称不是规范的一部分,只有open()
are intended to be used as keyword arguments.open()
的参数可以用作关键字参数。
The following table summarizes the ABCs provided by the 下表总结了io
module:io
模块提供的抽象基类:
|
|
|
|
---|---|---|---|
|
|
||
|
|
||
|
|
||
|
|
I/O Base Classes输入/输出基类¶
-
class
io.
IOBase
¶ The abstract base class for all I/O classes.所有I/O类的抽象基类。This class provides empty abstract implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.该类为派生类可以选择性重写的许多方法提供空的抽象实现;默认实现表示无法读取、写入或查找的文件。Even though尽管IOBase
does not declareread()
orwrite()
because their signatures will vary, implementations and clients should consider those methods part of the interface.IOBase
不声明read()
或write()
,因为它们的签名会有所不同,但实现和客户端应该将这些方法视为接口的一部分。Also, implementations may raise a此外,当调用不支持的操作时,实现可能会引发ValueError
(orUnsupportedOperation
) when operations they do not support are called.ValueError
(或UnsupportedOperation
)。The basic type used for binary data read from or written to a file is从文件读取或写入二进制数据的基本类型是bytes
.bytes
。Other bytes-like objects are accepted as method arguments too.其他类字节对象也被接受为方法参数。Text I/O classes work with文本输入/输出类处理str
data.str
数据。Note that calling any method (even inquiries) on a closed stream is undefined.请注意,在封闭流上调用任何方法(甚至查询)都是未定义的。Implementations may raise在这种情况下,实现可能会引发ValueError
in this case.ValueError
。IOBase
(and its subclasses) supports the iterator protocol, meaning that an(及其子类)支持迭代器协议,这意味着可以对IOBase
object can be iterated over yielding the lines in a stream.IOBase
对象进行迭代,从而生成流中的行。Lines are defined slightly differently depending on whether the stream is a binary stream (yielding bytes), or a text stream (yielding character strings).根据流是二进制流(产生字节)还是文本流(产生字符串),行的定义略有不同。See请参见下面的readline()
below.readline()
。IOBase
is also a context manager and therefore supports the也是上下文管理器,因此支持with
statement.with
语句。In this example, file is closed after the在本例中,with
statement’s suite is finished—even if an exception occurs:with
语句的套件完成后,即使发生异常,file也会关闭:with open('spam.txt', 'w') as file:
file.write('Spam and eggs!')IOBase
provides these data attributes and methods:提供以下数据属性和方法:-
close
()¶ Flush and close this stream.冲洗并关闭此流。This method has no effect if the file is already closed.如果文件已关闭,则此方法无效。Once the file is closed, any operation on the file (e.g. reading or writing) will raise a一旦文件关闭,对文件的任何操作(如读取或写入)都将引发ValueError
.ValueError
。As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.为了方便起见,允许多次调用此方法;但是,只有第一次调用才会产生效果。
-
closed
¶ 如果流已关闭,则为True
if the stream is closed.True
。
-
fileno
()¶ Return the underlying file descriptor (an integer) of the stream if it exists.返回流的基础文件描述符(整数)(如果存在)。An如果IO对象不使用文件描述符,则会引发OSError
is raised if the IO object does not use a file descriptor.OSError
。
-
flush
()¶ Flush the write buffers of the stream if applicable.如果适用,刷新流的写入缓冲区。This does nothing for read-only and non-blocking streams.这对只读和非阻塞流没有任何作用。
-
isatty
()¶ Return如果流是交互式的(即连接到终端/tty设备),则返回True
if the stream is interactive (i.e., connected to a terminal/tty device).True
。
-
readable
()¶ Return如果可以读取流,则返回True
if the stream can be read from.True
。If如果为False
,read()
will raiseOSError
.False
,read()
将引发OSError
。
-
readline
(size=- 1, /)¶ Read and return one line from the stream.读取并返回流中的一行。If size is specified, at most size bytes will be read.如果指定了size,则最多读取大小字节。The line terminator is always对于二进制文件,行终止符始终为b'\n'
for binary files; for text files, the newline argument toopen()
can be used to select the line terminator(s) recognized.b'\n'
;对于文本文件,可以对open()
使用newline
参数来选择识别的行终止符。
-
readlines
(hint=- 1, /)¶ Read and return a list of lines from the stream.读取并返回流中的行列表。hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.可以指定hint来控制读取的行数:如果所有行的总大小(以字节/字符为单位)远远超过hint,则不会读取更多的行。hint values of0
or less, as well asNone
, are treated as no hint.0
或更小的hint值以及None
都被视为无提示。Note that it’s already possible to iterate on file objects using请注意,已经可以使用for line in file: ...
without callingfile.readlines()
.for line in file: ...
对文件对象进行迭代,而不调用file.readlines()
。
-
seek
(offset, whence=SEEK_SET)¶ Change the stream position to the given byte offset.将流位置更改为给定的字节offset。offsetis interpreted relative to the position indicated by whence.相对于whence指示的位置进行解释。The default value for whence iswhence的默认值为SEEK_SET
.SEEK_SET
。Values for whence are:其中的whence值为:SEEK_SET
or或0
–start of the stream (the default); offset should be zero or positive流的开始(默认);offset应为零或正SEEK_CUR
or或1
–current stream position; offset may be negative当前流位置;offset可能为负SEEK_END
or或2
–end of the stream; offset is usually negative流的末端;offset通常为负值
Return the new absolute position.返回新的绝对位置。New in version 3.1.版本3.1中新增。TheSEEK_*
constants.SEEK_*
常量。New in version 3.3.版本3.3中新增。Some operating systems could support additional values, like一些操作系统可以支持其他值,如os.SEEK_HOLE
oros.SEEK_DATA
.os.SEEK_HOLE
或os.SEEK_DATA
。The valid values for a file could depend on it being open in text or binary mode.文件的有效值可能取决于它是否以文本或二进制模式打开。
-
seekable
()¶ Return如果流支持随机访问,则返回True
if the stream supports random access.True
。If如果为False
,seek()
,tell()
andtruncate()
will raiseOSError
.False
,seek()
、tell()
和truncate()
将引发OSError
。
-
tell
()¶ Return the current stream position.返回当前流位置。
-
truncate
(size=None)¶ Resize the stream to the given size in bytes (or the current position if size is not specified).将流大小调整为以字节为单位的给定size(如果未指定size,则调整为当前位置)。The current stream position isn’t changed.当前流位置未更改。This resizing can extend or reduce the current file size.此调整大小可以扩展或减小当前文件大小。In case of extension, the contents of the new file area depend on the platform (on most systems, additional bytes are zero-filled).在扩展的情况下,新文件区域的内容取决于平台(在大多数系统上,额外的字节是零填充的)。The new file size is returned.将返回新的文件大小。Changed in version 3.5:版本3.5中更改:Windows will now zero-fill files when extending.扩展时,Windows现在将零填充文件。
-
writable
()¶ Return如果流支持写入,则返回True
if the stream supports writing.True
。If如果为False
,write()
andtruncate()
will raiseOSError
.False
,write()
和truncate()
将引发OSError
。
-
writelines
(lines)¶ Write a list of lines to the stream.将行列表写入流。Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.没有添加行分隔符,因此通常提供的每一行的末尾都有行分隔符。
-
-
class
io.
RawIOBase
¶ Base class for raw binary streams.原始二进制流的基类。It inherits它继承了IOBase
.IOBase
。Raw binary streams typically provide low-level access to an underlying OS device or API, and do not try to encapsulate it in high-level primitives (this functionality is done at a higher-level in buffered binary streams and text streams, described later in this page).原始二进制流通常提供对底层OS设备或API的低级访问,并且不尝试将其封装在高级原语中(此功能在缓冲二进制流和文本流中的更高级别上完成,本页稍后将介绍)。RawIOBase
provides these methods in addition to those from除了IOBase
:IOBase
提供的方法外,还提供以下方法:-
read
(size=- 1, /)¶ Read up to size bytes from the object and return them.从对象读取最多size的字节并返回它们。As a convenience, if size is unspecified or -1, all bytes until EOF are returned.为方便起见,如果size未指定或为-1,则返回EOF之前的所有字节。Otherwise, only one system call is ever made.否则,只进行一次系统调用。Fewer than size bytes may be returned if the operating system call returns fewer than size bytes.如果操作系统调用返回的字节数小于size,则返回的字节数可能小于size。If 0 bytes are returned, and size was not 0, this indicates end of file.若返回0字节,且size不是0,则表示文件结束。If the object is in non-blocking mode and no bytes are available,如果对象处于非阻塞模式且没有可用字节,则会返回None
is returned.None
。The default implementation defers to默认实现遵从readall()
andreadinto()
.readall()
和readinto()
。
-
readall
()¶ Read and return all the bytes from the stream until EOF, using multiple calls to the stream if necessary.读取并返回流中的所有字节,直到EOF,如有必要,使用对流的多次调用。
-
readinto
(b)¶ Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read.将字节读入预分配的可写类字节对象b,然后返回读取的字节数。For example, b might be a例如,b可能是bytearray
.bytearray
。If the object is in non-blocking mode and no bytes are available,如果对象处于非阻塞模式且没有可用字节,则将返回None
is returned.None
。
-
write
(b)¶ Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written.将给定的类字节对象b写入底层原始流,并返回写入的字节数。This can be less than the length of b in bytes, depending on specifics of the underlying raw stream, and especially if it is in non-blocking mode.这可以小于b的字节长度,具体取决于底层原始流的具体情况,尤其是在非阻塞模式下。如果原始流设置为不阻塞,并且没有单个字节可以轻易写入,则返回None
is returned if the raw stream is set not to block and no single byte could be readily written to it.None
。The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.调用方可以在该方法返回后释放或修改b,因此实现应该只在方法调用期间访问b。
-
-
class
io.
BufferedIOBase
¶ Base class for binary streams that support some kind of buffering.支持某种缓冲的二进制流的基类。It inherits它继承了IOBase
.IOBase
。The main difference with与RawIOBase
is that methodsread()
,readinto()
andwrite()
will try (respectively) to read as much input as requested or to consume all given output, at the expense of making perhaps more than one system call.RawIOBase
的主要区别在于,read()
、readinto()
和write()
方法将尝试(分别)读取请求的尽可能多的输入或消耗所有给定的输出,代价可能是进行多个系统调用。In addition, those methods can raise此外,如果底层原始流处于非阻塞模式,并且无法获取或提供足够的数据,那么这些方法可能会引发BlockingIOError
if the underlying raw stream is in non-blocking mode and cannot take or give enough data; unlike theirRawIOBase
counterparts, they will never returnNone
.BlockingIOError
;与RawIOBase
的对手不同,他们永远不会返回任何结果。Besides, the此外,read()
method does not have a default implementation that defers toreadinto()
.read()
方法没有遵从readinto()
的默认实现。A typical典型的BufferedIOBase
implementation should not inherit from aRawIOBase
implementation, but wrap one, likeBufferedWriter
andBufferedReader
do.BufferedIOBase
实现不应该继承自RawIOBase
实现,而应该像BufferedWriter
和BufferedReader
那样包装一个实现。除了BufferedIOBase
provides or overrides these data attributes and methods in addition to those fromIOBase
:IOBase
中的数据属性和方法之外,BufferedIOBase
还提供或重写这些数据属性和方法:-
raw
¶ The underlying raw stream (aRawIOBase
instance) thatBufferedIOBase
deals with.BufferedIOBase
处理的底层原始流(一个RawIOBase
实例)。This is not part of the这不是BufferedIOBase
API and may not exist on some implementations.BufferedIOBase
API的一部分,在某些实现中可能不存在。
-
detach
()¶ Separate the underlying raw stream from the buffer and return it.将底层原始流与缓冲区分离并返回它。After the raw stream has been detached, the buffer is in an unusable state.分离原始流后,缓冲区处于不可用状态。Some buffers, like有些缓冲区(如BytesIO
, do not have the concept of a single raw stream to return from this method.BytesIO
)没有从该方法返回的单个原始流的概念。They raise它们引发了UnsupportedOperation
.UnsupportedOperation
。New in version 3.1.版本3.1中新增。
-
read
(size=- 1)¶ Read and return up to size bytes.读取并返回最多size字节。If the argument is omitted,如果省略参数、参数为None
, or negative, data is read and returned until EOF is reached.None
或为负,则读取并返回数据,直到达到EOF。An empty如果流已经处于EOF,则返回空bytes
object is returned if the stream is already at EOF.bytes
对象。If the argument is positive, and the underlying raw stream is not interactive, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first).如果参数为正,并且基础原始流不是交互式的,则可能会发出多个原始读取以满足字节计数(除非首先达到EOF)。But for interactive raw streams, at most one raw read will be issued, and a short result does not imply that EOF is imminent.但对于交互式原始流,最多会发出一次原始读取,短的结果并不意味着EOF即将到来。A如果底层原始流处于非阻塞模式,并且当前没有可用数据,则会引发BlockingIOError
is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.BlockingIOError
。
-
read1
([size])¶ Read and return up to size bytes, with at most one call to the underlying raw stream’s读取并返回最多size字节,最多一次调用底层原始流的read()
(orreadinto()
) method.read()
(或readinto()
)方法。This can be useful if you are implementing your own buffering on top of a如果要在BufferedIOBase
object.BufferedIOBase
对象上实现自己的缓冲,这可能很有用。If size is如果size为-1
(the default), an arbitrary number of bytes are returned (more than zero unless EOF is reached).-1
(默认值),则返回任意数量的字节(除非达到EOF,否则大于零)。
-
readinto
(b, /)¶ Read bytes into a pre-allocated, writable bytes-like object b and return the number of bytes read.将字节读入预分配的可写类字节对象b,并返回读取的字节数。For example, b might be a例如,b可能是bytearray
.bytearray
。Like与read()
, multiple reads may be issued to the underlying raw stream, unless the latter is interactive.read()
一样,可以向底层原始流发出多次读取,除非后者是交互式的。A如果底层原始流处于非阻塞模式,并且当前没有可用数据,则会引发BlockingIOError
is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.BlockingIOError
。
-
readinto1
(b, /)¶ Read bytes into a pre-allocated, writable bytes-like object b, using at most one call to the underlying raw stream’s最多使用一次对底层原始流的read()
(orreadinto()
) method.read()
(或readinto()
)方法的调用,将字节读入预分配的可写类字节对象b。Return the number of bytes read.返回读取的字节数。A如果底层原始流处于非阻塞模式,并且当前没有可用数据,则会引发BlockingIOError
is raised if the underlying raw stream is in non blocking-mode, and has no data available at the moment.BlockingIOError
。New in version 3.5.版本3.5中新增。
-
write
(b)¶ Write the given bytes-like object, b, and return the number of bytes written (always equal to the length of b in bytes, since if the write fails an写入给定的类字节对象b,并返回写入的字节数(始终等于以字节为单位的b的长度,因为如果写入失败,将引发OSError
will be raised).OSError
)。Depending on the actual implementation, these bytes may be readily written to the underlying stream, or held in a buffer for performance and latency reasons.根据实际实现,这些字节可能很容易写入底层流,或者出于性能和延迟原因保存在缓冲区中。When in non-blocking mode, a在非阻塞模式下,如果需要将数据写入原始流,但它无法在不阻塞的情况下接受所有数据,则会引发BlockingIOError
is raised if the data needed to be written to the raw stream but it couldn’t accept all the data without blocking.BlockingIOError
。The caller may release or mutate b after this method returns, so the implementation should only access b during the method call.调用方可以在该方法返回后释放或修改b,因此实现应该只在方法调用期间访问b。
-
Raw File 原始文件I/O¶
-
class
io.
FileIO
(name, mode='r', closefd=True, opener=None)¶ A raw binary stream representing an OS-level file containing bytes data.表示包含字节数据的OS级文件的原始二进制流。It inherits它继承了RawIOBase
.RawIOBase
。The name can be one of two things:name可以是以下两种名称之一:a character string or表示要打开的文件路径的字符串或bytes
object representing the path to the file which will be opened.bytes
对象。In this case closefd must be在这种情况下,closefd必须为True
(the default) otherwise an error will be raised.True
(默认值),否则将引发错误。an integer representing the number of an existing OS-level file descriptor to which the resulting一个整数,表示生成的FileIO
object will give access.FileIO
对象将授予其访问权限的现有OS级文件描述符的数目。When the FileIO object is closed this fd will be closed as well, unless closefd is set to当FileIO对象关闭时,此fd也将关闭,除非closefd设置为False
.False
。
The mode can be读取(默认)、写入、独占创建或附加的mode可以是'r'
,'w'
,'x'
or'a'
for reading (default), writing, exclusive creation or appending.'r'
、'w'
、'x'
或'a'
。The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing.如果文件在打开进行写入或附加时不存在,将创建该文件;当打开进行写入时,它将被截断。如果文件在打开进行创建时已存在,则会引发FileExistsError
will be raised if it already exists when opened for creating.FileExistsError
。Opening a file for creating implies writing, so this mode behaves in a similar way to打开文件进行创建意味着写入,因此此模式的行为方式与'w'
.'w'
类似。Add a在模式中添加'+'
to the mode to allow simultaneous reading and writing.'+'
以允许同时读写。The此类上的read()
(when called with a positive argument),readinto()
andwrite()
methods on this class will only make one system call.read()
(当使用正参数调用时)、readinto()
和write()
方法将只进行一次系统调用。A custom opener can be used by passing a callable as opener.可以通过将可调用的作为opener传递来使用自定义开启器。The underlying file descriptor for the file object is then obtained by calling opener with (name, flags).然后通过使用(name、flags志)调用opener来获取文件对象的底层文件描述符。opener must return an open file descriptor (passingopener必须返回一个打开的文件描述符(将os.open
as opener results in functionality similar to passingNone
).os.open
作为opener传递会导致类似于不传递任何描述符的功能)。The newly created file is non-inheritable.新创建的文件不可继承。See the有关使用opener参数的示例,请参阅open()
built-in function for examples on using the opener parameter.open()
内置函数。Changed in version 3.3:版本3.3中更改:The opener parameter was added.添加了opener参数。The添加了'x'
mode was added.'x'
模式。Changed in version 3.4:版本3.4中更改:The file is now non-inheritable.该文件现在不可继承。除了来自FileIO
provides these data attributes in addition to those fromRawIOBase
andIOBase
:RawIOBase
和IOBase
的数据属性之外,FileIO
还提供以下数据属性:-
mode
¶ The mode as given in the constructor.构造函数中给定的模式。
-
name
¶ The file name.文件名。This is the file descriptor of the file when no name is given in the constructor.当构造函数中没有给出名称时,这是文件的文件描述符。
Buffered Streams缓冲流¶
Buffered I/O streams provide a higher-level interface to an I/O device than raw I/O does.缓冲输入/输出流比原始输入/输出为输入/输出设备提供更高级别的接口。
-
class
io.
BytesIO
([initial_bytes])¶ A binary stream using an in-memory bytes buffer.使用内存字节缓冲区的二进制流。It inherits它继承了BufferedIOBase
.BufferedIOBase
。The buffer is discarded when the调用close()
method is called.close()
方法时,将丢弃缓冲区。The optional argument initial_bytes is a bytes-like object that contains initial data.可选参数initial_bytes是一个类字节对象,包含初始数据。除了来自BytesIO
provides or overrides these methods in addition to those fromBufferedIOBase
andIOBase
:BufferedIOBase
和IOBase
的方法外,BytesIO
还提供或重写这些方法:-
getbuffer
()¶ Return a readable and writable view over the contents of the buffer without copying them.返回缓冲区内容的可读写视图,而不复制它们。Also, mutating the view will transparently update the contents of the buffer:此外,更改视图将透明地更新缓冲区的内容:>>> b = io.BytesIO(b"abcdef")
>>> view = b.getbuffer()
>>> view[2:4] = b"56"
>>> b.getvalue()
b'ab56ef'Note
As long as the view exists, the只要视图存在,就无法调整或关闭BytesIO
object cannot be resized or closed.BytesIO
对象的大小。New in version 3.2.版本3.2中新增。
-
read1
([size, ]/)¶ In在BytesIO
, this is the same asread()
.BytesIO
中,这与read()
相同。Changed in version 3.7:版本3.7中更改:The size argument is now optional.size参数现在是可选的。
-
readinto1
(b)¶ In在BytesIO
, this is the same asreadinto()
.BytesIO
中,这与readinto()
相同。New in version 3.5.版本3.5中新增。
-
-
class
io.
BufferedReader
(raw, buffer_size=DEFAULT_BUFFER_SIZE)¶ A buffered binary stream providing higher-level access to a readable, non seekable一种缓冲的二进制流,提供对可读的、不可查找的RawIOBase
raw binary stream.RawIOBase
原始二进制流的更高级访问。It inherits它继承了BufferedIOBase
.BufferedIOBase
。When reading data from this object, a larger amount of data may be requested from the underlying raw stream, and kept in an internal buffer.从该对象读取数据时,可能会从底层原始流请求更多数据,并将其保存在内部缓冲区中。The buffered data can then be returned directly on subsequent reads.然后,可以在后续读取时直接返回缓冲数据。The constructor creates a构造函数为给定的可读原始流和buffer_size创建一个BufferedReader
for the given readable raw stream and buffer_size.BufferedReader
。If buffer_size is omitted,如果省略buffer_size,则使用DEFAULT_BUFFER_SIZE
is used.DEFAULT_BUFFER_SIZE
。除了来自BufferedReader
provides or overrides these methods in addition to those fromBufferedIOBase
andIOBase
:BufferedIOBase
和IOBase
的方法之外,BufferedReader
还提供或重写这些方法:-
peek
([size])¶ Return bytes from the stream without advancing the position.从流返回字节,而不推进位置。At most one single read on the raw stream is done to satisfy the call.为了满足调用,最多对原始流执行一次读取。The number of bytes returned may be less or more than requested.返回的字节数可能小于或大于请求的字节数。
-
read
([size])¶ Read and return size bytes, or if size is not given or negative, until EOF or if the read call would block in non-blocking mode.读取并返回size字节,或者如果未给定size或size为负,则直到EOF,或者如果读取调用将在非阻塞模式下阻塞。
-
read1
([size])¶ Read and return up to size bytes with only one call on the raw stream.只需对原始流进行一次调用,即可读取并返回最多size的字节。If at least one byte is buffered, only buffered bytes are returned.如果至少缓冲了一个字节,则只返回缓冲的字节。Otherwise, one raw stream read call is made.否则,将进行一个原始流读取调用。Changed in version 3.7:版本3.7中更改:The size argument is now optional.size参数现在是可选的。
-
-
class
io.
BufferedWriter
(raw, buffer_size=DEFAULT_BUFFER_SIZE)¶ A buffered binary stream providing higher-level access to a writeable, non seekable一种缓冲二进制流,提供对可写、不可查找的RawIOBase
raw binary stream.RawIOBase
原始二进制流的高级访问。It inherits它继承了BufferedIOBase
.BufferedIOBase
。When writing to this object, data is normally placed into an internal buffer.当写入此对象时,数据通常被放入内部缓冲区。The buffer will be written out to the underlying缓冲区将在各种条件下写入底层RawIOBase
object under various conditions, including:RawIOBase
对象,包括:when the buffer gets too small for all pending data;当缓冲区对于所有挂起的数据来说太小时;when a请求seek()
is requested (forBufferedRandom
objects);seek()
时(对于BufferedRandom
对象);when the当BufferedWriter
object is closed or destroyed.BufferedWriter
对象关闭或销毁时。
The constructor creates a构造函数为给定的可写原始流创建一个BufferedWriter
for the given writeable raw stream.BufferedWriter
。If the buffer_size is not given, it defaults to如果未指定buffer_size,则默认为DEFAULT_BUFFER_SIZE
.DEFAULT_BUFFER_SIZE
。除了来自BufferedWriter
provides or overrides these methods in addition to those fromBufferedIOBase
andIOBase
:BufferedIOBase
和IOBase
的方法之外,BufferedWriter
还提供或重写这些方法:-
flush
()¶ Force bytes held in the buffer into the raw stream.强制将缓冲区中保留的字节放入原始流。A如果原始流阻塞,则应引发BlockingIOError
should be raised if the raw stream blocks.BlockingIOError
。
-
write
(b, /)¶ Write the bytes-like object, b, and return the number of bytes written.写入类字节对象b,并返回写入的字节数。When in non-blocking mode, a在非阻塞模式下,如果需要写出缓冲区,但原始流阻塞,则会引发BlockingIOError
is raised if the buffer needs to be written out but the raw stream blocks.BlockingIOError
。
-
class
io.
BufferedRandom
(raw, buffer_size=DEFAULT_BUFFER_SIZE)¶ A buffered binary stream providing higher-level access to a seekable一种缓冲的二进制流,提供对可查找的RawIOBase
raw binary stream.RawIOBase
原始二进制流的更高级访问。It inherits它继承了BufferedReader
andBufferedWriter
.BufferedReader
和BufferedWriter
。The constructor creates a reader and writer for a seekable raw stream, given in the first argument.构造函数为第一个参数中给出的可查找的原始流创建读写器。If the buffer_size is omitted it defaults to如果省略buffer_size,则默认为DEFAULT_BUFFER_SIZE
.DEFAULT_BUFFER_SIZE
。BufferedRandom
is capable of anythingBufferedReader
orBufferedWriter
can do.BufferedRandom
能够完成BufferedReader
或BufferedWriter
所能做的任何事情。In addition,此外,保证实现seek()
andtell()
are guaranteed to be implemented.seek()
和tell()
。
-
class
io.
BufferedRWPair
(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, /)¶ A buffered binary stream providing higher-level access to two non seekable一种缓冲二进制流,提供对两个不可查找的RawIOBase
raw binary streams—one readable, the other writeable.RawIOBase
原始二进制流的更高级访问,一个可读,另一个可写。It inherits它继承了BufferedIOBase
.BufferedIOBase
。reader and writer arereader和writer是分别可读写的RawIOBase
objects that are readable and writeable respectively.RawIOBase
对象。If the buffer_size is omitted it defaults to如果省略buffer_size,则默认为DEFAULT_BUFFER_SIZE
.DEFAULT_BUFFER_SIZE
。BufferedRWPair
implements all ofBufferedIOBase
's methods except fordetach()
, which raisesUnsupportedOperation
.BufferedRWPair
实现了BufferedIOBase
的所有方法,但detach()
除外,这会引发不支持操作。Warning
BufferedRWPair
does not attempt to synchronize accesses to its underlying raw streams.不会尝试同步对其底层原始流的访问。You should not pass it the same object as reader and writer; use您不应将其作为读写器传递给同一对象;改用BufferedRandom
instead.BufferedRandom
。
Text I/O¶
-
class
io.
TextIOBase
¶ Base class for text streams.文本流的基类。This class provides a character and line based interface to stream I/O.此类为流I/O提供基于字符和行的接口。It inherits它继承了IOBase
.IOBase
。除了提供或重写TextIOBase
provides or overrides these data attributes and methods in addition to those fromIOBase
:IOBase
中的数据属性和方法外,TextIOBase
还提供或重写这些数据属性和方法:-
encoding
¶ The name of the encoding used to decode the stream’s bytes into strings, and to encode strings into bytes.用于将流的字节解码为字符串和将字符串编码为字节的编码的名称。
-
errors
¶ The error setting of the decoder or encoder.解码器或编码器的错误设置。
-
newlines
¶ A string, a tuple of strings, or字符串、字符串元组或None
, indicating the newlines translated so far.None
,表示迄今为止已翻译的换行符。Depending on the implementation and the initial constructor flags, this may not be available.根据实现和初始构造函数标志,这可能不可用。
-
buffer
¶ The underlying binary buffer (aBufferedIOBase
instance) thatTextIOBase
deals with.TextIOBase
处理的底层二进制缓冲区(BufferedIOBase
实例)。This is not part of the这不是TextIOBase
API and may not exist in some implementations.TextIOBase
API的一部分,在某些实现中可能不存在。
-
detach
()¶ Separate the underlying binary buffer from the将底层二进制缓冲区与TextIOBase
and return it.TextIOBase
分离并返回它。After the underlying buffer has been detached, the分离底层缓冲区后,TextIOBase
is in an unusable state.TextIOBase
处于不可用状态。Some一些TextIOBase
implementations, likeStringIO
, may not have the concept of an underlying buffer and calling this method will raiseUnsupportedOperation
.TextIOBase
实现,如StringIO
,可能没有底层缓冲区的概念,调用此方法将导致UnsupportedOperation
。New in version 3.1.版本3.1中新增。
-
read
(size=- 1, /)¶ Read and return at most size characters from the stream as a single作为单个str
.str
从流中读取并返回最大size的字符。If size is negative or如果size为负或None
, reads until EOF.None
,则读取直到EOF。
-
readline
(size=- 1)¶ Read until newline or EOF and return a single读到换行符或EOF并返回一个str
.str
。If the stream is already at EOF, an empty string is returned.如果流已经处于EOF,则返回空字符串。If size is specified, at most size characters will be read.如果指定了size,则最多读取size字符。
-
seek
(offset, whence=SEEK_SET)¶ Change the stream position to the given offset.将流位置更改为给定offset。Behaviour depends on the whence parameter.行为取决于whence参数。The default value for whence iswhence的默认值为SEEK_SET
.SEEK_SET
。SEEK_SET
or或0
: seek from the start of the stream (the default); offset must either be a number returned by:从流的开始搜索(默认);offset必须是TextIOBase.tell()
, or zero.TextIOBase.tell()
返回的数字或零。Any other offset value produces undefined behaviour.任何其他offset都会产生未定义的行为。SEEK_CUR
or或1
: “seek” to the current position; offset must be zero, which is a no-operation (all other values are unsupported).:“seek”到当前位置;offset必须为零,这是一个无操作(不支持所有其他值)。SEEK_END
or或2
: seek to the end of the stream; offset must be zero (all other values are unsupported).:搜索到流的末端;offset必须为零(不支持所有其他值)。
Return the new absolute position as an opaque number.以不透明数字返回新的绝对位置。New in version 3.1.版本3.1中新增。TheSEEK_*
constants.SEEK_*
常量
-
tell
()¶ Return the current stream position as an opaque number.以不透明数字返回当前流位置。The number does not usually represent a number of bytes in the underlying binary storage.该数字通常不表示基础二进制存储中的字节数。
-
write
(s)¶ Write the string s to the stream and return the number of characters written.将字符串s写入流并返回写入的字符数。
-
-
class
io.
TextIOWrapper
(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)¶ A buffered text stream providing higher-level access to a一种缓冲文本流,提供对BufferedIOBase
buffered binary stream.BufferedIOBase
缓冲二进制流的更高级访问。It inherits它继承TextIOBase
.TextIOBase
。encoding
gives the name of the encoding that the stream will be decoded or encoded with.提供流将被解码或编码的编码的名称。It defaults to它默认为locale.getpreferredencoding(False)
.locale.getpreferredencoding(False)
。encoding="locale"
can be used to specify the current locale’s encoding explicitly.可用于显式指定当前语言环境的编码。See Text Encoding for more information.有关详细信息,请参阅文本编码。errors
is an optional string that specifies how encoding and decoding errors are to be handled.是一个可选字符串,指定如何处理编码和解码错误。Pass如果存在编码错误,则传递'strict'
to raise aValueError
exception if there is an encoding error (the default ofNone
has the same effect), or pass'ignore'
to ignore errors.'strict'
以引发ValueError
异常(默认值None
具有相同的效果),或者传递'ignore'
以忽略错误。(Note that ignoring encoding errors can lead to data loss.)(请注意,忽略编码错误可能会导致数据丢失。)'replace'
causes a replacement marker (such as'?'
) to be inserted where there is malformed data.'replace'
导致在数据格式错误的地方插入替换标记(如“'?'
”)。'backslashreplace'
causes malformed data to be replaced by a backslashed escape sequence.导致格式错误的数据被反斜杠转义序列替换。When writing,写入时,'xmlcharrefreplace'
(replace with the appropriate XML character reference) or'namereplace'
(replace with\N{...}
escape sequences) can be used.'xmlcharrefreplace'
(替换为适当的XML字符引用)或'namereplace'
(替换为\N{...}
)可以使用转义序列)。Any other error handling name that has been registered with已向codecs.register_error()
is also valid.codecs.register_error()
注册的任何其他错误处理名称也有效。newline
controls how line endings are handled.控制如何处理行尾。It can be它可以是None
,''
,'\n'
,'\r'
, and'\r\n'
.None
、''
、'\n'
、'\r'
和'\r\n'
。It works as follows:其工作原理如下:When reading input from the stream, if newline is从流中读取输入时,如果newline为None
, universal newlines mode is enabled.None
,则启用通用换行符模式。Lines in the input can end in输入中的行可以以'\n'
,'\r'
, or'\r\n'
, and these are translated into'\n'
before being returned to the caller.'\n'
、'\r'
或'\r\n'
结尾,这些行在返回给调用者之前会被转换为'\n'
。If newline is如果newline为''
, universal newlines mode is enabled, but line endings are returned to the caller untranslated.''
,则启用通用换行符模式,但换行符将返回给未翻译的调用者。If newline has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.如果newline具有任何其他合法值,则输入行仅由给定字符串终止,并且行尾将返回给未翻译的调用者。When writing output to the stream, if newline is将输出写入流时,如果newline为None
, any'\n'
characters written are translated to the system default line separator,os.linesep
.None
,则写入的任何'\n'
字符都将转换为系统默认的行分隔符os.linesep
。If newline is如果newline为''
or'\n'
, no translation takes place.''
或'\n'
,则不会进行转换。If newline is any of the other legal values, any如果newline是任何其他合法值,则写入的任何'\n'
characters written are translated to the given string.'\n'
字符都将转换为给定字符串。
If line_buffering is如果line_buffering为True
,flush()
is implied when a call to write contains a newline character or a carriage return.True
,则当write调用包含换行符或回车符时,将暗示flush()
。If write_through is如果write_through为True
, calls towrite()
are guaranteed not to be buffered: any data written on theTextIOWrapper
object is immediately handled to its underlying binary buffer.True
,则保证不会缓冲对write()
的调用:在TextIOWrapper
对象上写入的任何数据都会立即处理到其底层二进制buffer。Changed in version 3.3:版本3.3中更改:The write_through argument has been added.已添加write_through参数。Changed in version 3.3:版本3.3中更改:The default encoding is now默认encoding现在是locale.getpreferredencoding(False)
instead oflocale.getpreferredencoding()
.locale.getpreferredencoding(False)
,而不是locale.getpreferredencoding()
。Don’t change temporary the locale encoding using不要使用locale.setlocale()
, use the current locale encoding instead of the user preferred encoding.locale.setlocale()
临时更改区域设置编码,请使用当前区域设置编码,而不是用户首选的编码。Changed in version 3.10:版本3.10中更改:The encoding argument now supports theencoding参数现在支持"locale"
dummy encoding name."locale"
伪编码名称。除了提供来自TextIOWrapper
provides these data attributes and methods in addition to those fromTextIOBase
andIOBase
:TextIOBase
和IOBase
的数据属性和方法外,TextIOWrapper
还提供以下数据属性和方法:-
line_buffering
¶ Whether line buffering is enabled.是否启用行缓冲。
-
write_through
¶ Whether writes are passed immediately to the underlying binary buffer.写入是否立即传递到基础二进制缓冲区。New in version 3.7.版本3.7中新增。
-
reconfigure
(*[, encoding][, errors][, newline][, line_buffering][, write_through])¶ Reconfigure this text stream using new settings for encoding, errors, newline, line_buffering and write_through.使用encoding、errors、newline、line_buffering和write_through的新设置重新配置此文本流。Parameters not specified keep current settings, except未指定的参数保持当前设置,除非指定了encoding但未指定errors时使用errors='strict'
is used when encoding is specified but errors is not specified.errors='strict'
。It is not possible to change the encoding or newline if some data has already been read from the stream.如果已经从流中读取了一些数据,则无法更改编码或换行符。On the other hand, changing encoding after write is possible.另一方面,可以在写入后更改编码。This method does an implicit stream flush before setting the new parameters.此方法在设置新参数之前执行隐式流刷新。New in version 3.7.版本3.7中新增。
-
class
io.
StringIO
(initial_value='', newline='\n')¶ A text stream using an in-memory text buffer.使用内存中文本缓冲区的文本流。It inherits它继承了TextIOBase
.TextIOBase
。The text buffer is discarded when the调用close()
method is called.close()
方法时,将丢弃文本缓冲区。The initial value of the buffer can be set by providing initial_value.可以通过提供initial_value来设置缓冲区的初始值。If newline translation is enabled, newlines will be encoded as if by如果启用了换行转换,则换行将按照write()
.write()
进行编码。The stream is positioned at the start of the buffer.流位于缓冲区的开头。The newline argument works like that ofnewline参数的工作方式与TextIOWrapper
, except that when writing output to the stream, if newline isNone
, newlines are written as\n
on all platforms.TextIOWrapper
类似,只是在将输出写入流时,如果newline为None
,则所有平台上的换行都将写入为\n
。除了提供来自StringIO
provides this method in addition to those fromTextIOBase
andIOBase
:TextIOBase
和IOBase
的方法外,StringIO
还提供了以下方法:-
getvalue
()¶ Return a返回包含缓冲区全部内容的str
containing the entire contents of the buffer.str
。Newlines are decoded as if by尽管流的位置没有改变,但换行符被解码为read()
, although the stream position is not changed.read()
。
Example usage:示例用法:import io
output = io.StringIO()
output.write('First line.\n')
print('Second line.', file=output)
# Retrieve file contents -- this will be
# 'First line.\nSecond line.\n'
contents = output.getvalue()
# Close object and discard memory buffer --
# .getvalue() will now raise an exception.
output.close()-
-
class
io.
IncrementalNewlineDecoder
¶ A helper codec that decodes newlines for universal newlines mode.为通用换行符模式解码换行符的辅助编解码器。It inherits它继承了codecs.IncrementalDecoder
.codecs.IncrementalDecoder
。
Performance性能¶
This section discusses the performance of the provided concrete I/O implementations.本节讨论所提供的具体I/O实现的性能。
Binary 二进制的I/O¶
By reading and writing only large chunks of data even when the user asks for a single byte, buffered I/O hides any inefficiency in calling and executing the operating system’s unbuffered I/O routines. 通过仅读取和写入大数据块(即使用户请求一个字节),缓冲I/O隐藏了调用和执行操作系统无缓冲I/O例程的任何低效性。The gain depends on the OS and the kind of I/O which is performed. 增益取决于操作系统和执行的输入/输出类型。For example, on some modern OSes such as Linux, unbuffered disk I/O can be as fast as buffered I/O. 例如,在一些现代操作系统(如Linux)上,无缓冲磁盘I/O可以与缓冲I/O一样快。The bottom line, however, is that buffered I/O offers predictable performance regardless of the platform and the backing device. 然而,归根结底,缓冲I/O提供了可预测的性能,而与平台和支持设备无关。Therefore, it is almost always preferable to use buffered I/O rather than unbuffered I/O for binary data.因此,对于二进制数据,几乎总是最好使用缓冲I/O而不是无缓冲I/O。
Text I/O¶
Text I/O over a binary storage (such as a file) is significantly slower than binary I/O over the same storage, because it requires conversions between unicode and binary data using a character codec. 二进制存储(如文件)上的文本输入/输出比相同存储上的二进制输入/输出慢得多,因为它需要使用字符编解码器在unicode和二进制数据之间进行转换。This can become noticeable handling huge amounts of text data like large log files. 在处理大量文本数据(如大型日志文件)时,这可能会变得很明显。Also, 此外,由于使用了重建算法,TextIOWrapper.tell()
and TextIOWrapper.seek()
are both quite slow due to the reconstruction algorithm used.TextIOWrapper.tell()
和TextIOWrapper.seek()
都非常慢。
然而,StringIO
, however, is a native in-memory unicode container and will exhibit similar speed to BytesIO
.StringIO
是一个本机内存中的unicode容器,其速度将与BytesIO
相似。
Multi-threading多线程¶
FileIO
objects are thread-safe to the extent that the operating system calls (such as read(2)
under Unix) they wrap are thread-safe too.FileIO
对象是线程安全的,操作系统调用(如Unix下的read(2)
)也是线程安全的。
Binary buffered objects (instances of 二进制缓冲对象(BufferedReader
, BufferedWriter
, BufferedRandom
and BufferedRWPair
) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once.BufferedReader
、BufferedWriter
、BufferedRandom
和BufferedRWPair
的实例)使用锁保护其内部结构;因此,一次从多个线程调用它们是安全的。
TextIOWrapper
objects are not thread-safe.对象不是线程安全的。
Reentrancy可重入¶
Binary buffered objects (instances of 二进制缓冲对象(BufferedReader
, BufferedWriter
, BufferedRandom
and BufferedRWPair
) are not reentrant. BufferedReader
、BufferedWriter
、BufferedRandom
和BufferedRWPair
的实例)不可重入。While reentrant calls will not happen in normal situations, they can arise from doing I/O in a 虽然可重入调用在正常情况下不会发生,但它们可能是在signal
handler. signal
处理程序中进行I/O时产生的。If a thread tries to re-enter a buffered object which it is already accessing, a 如果线程尝试重新输入它已经在访问的缓冲对象,则会引发RuntimeError
is raised. RuntimeError
。Note this doesn’t prohibit a different thread from entering the buffered object.注意,这并不禁止其他线程进入缓冲对象。
The above implicitly extends to text files, since the 由于open()
function will wrap a buffered object inside a TextIOWrapper
. open()
函数将在TextIOWrapper
中包装一个缓冲对象,因此上述内容隐式扩展到文本文件。This includes standard streams and therefore affects the built-in 这包括标准流,因此也会影响内置的print()
function as well.print()
函数。