pythone IO.py 文件源代码

该博客介绍了Python的IO模块,主要用于处理数据流,包括文本数据流、二进制数据流和原始数据流。文中详细阐述了如何创建文本流,如使用`io.StringIO`和`open`函数,并讲解了二进制流的创建,如通过`open`函数以'rb'模式打开文件。此外,还提到了内存数据流,如`StringIO`和`BytesIO`,它们分别支持文本和二进制模式的读写操作。最后,讨论了`io.DEFAULT_BUFFER_SIZE`以及`open`函数的参数和用途。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#io 模块主要是提供了用于处理数据流的核心工具
'''
数据流:
    文本数据流 txt i/o
    二进制数据流 binary io
    原始数据流 raw io
'''
#创建文本流的方式
#方式1
import io
f = io.StringIO("some initial text data")
f.close()
#方式2
f=open("a.txt","r",encoding="utf-8")
#16.2.1.2. Binary I/O (also called *buffered I/O*)
'''
The easiest way to create a binary stream is with "open()" with "'b'"
in the mode string:
'''
f = open("myfile.jpg", "rb")
#  In-memory binary streams are also available as "BytesIO" objects:
f = io.BytesIO(b"some initial binary data: \x00\x01")

## 16.2.1.3. Raw I/O
#禁用无无缓冲io流的方式
f = open("myfile.jpg", "rb", buffering=0)
# High-level Module Interface  高级模块接口
"""
io.DEFAULT_BUFFER_SIZE

   An int containing the default buffer size used by the module's
   buffered I/O classes.  "open()" uses the file's blksize (as
   obtained by "os.stat()") if possible.
   包含模块缓冲I / O类使用的默认缓冲区大小的int。 如果可能,“open()”使用文件的blksize(由“os.stat()”获得)。
"""
print(io.DEFAULT_BUFFER_SIZE) #默认二进制文件的流的大小8192

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.
'''
16.2.2.1. In-memory streams 内存数据流
It is also possible to use a "str" or *bytes-like object* as a file
for both reading and writing.  For strings "StringIO" can be used like
a file opened in text mode.  "BytesIO" can be used like a file opened
in binary mode.  Both provide full read-write capabilities with random
access.

See also:

  "sys"
     contains the standard IO streams: "sys.stdin", "sys.stdout", and
     "sys.stderr".
'''


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值