Python io 模块允许我们管理与文件相关的输入和输出操作. 使用 IO 模块的优点是可用的类和功能使我们能够扩展功能,使写入 Unicode 数据。
Python IO 模块
我们可以使用 io 模块在 Python 中执行流和缓冲操作的方式有很多,我们在这里将展示很多例子来证明这一点。
Python 交换机
就像我们用变量做的那样,当我们使用 io 模块的 Byte IO 操作时,数据可以在内存缓冲器中存储为字节。
1import io
2
3stream_str = io.BytesIO(b"JournalDev Python: \x00\x01")
4print(stream_str.getvalue())
Let's see the output for this program: The
getvalue()
function just takes the value from the Buffer as a String.
Python 字符串
我们甚至可以使用StringIO
,这在使用方面非常类似于BytesIO
。
1import io
2
3data = io.StringIO()
4data.write('JournalDev: ')
5print('Python.', file=data)
6
7print(data.getvalue())
8
9data.close()
Let's see the output for this program: Notice that we even closed the buffer after we're done with the buffer. This helps save buffer memory as they store data in-memory. Also, we used the print method with an optional argument to specify an IO stream of the variable, which is perfectly compatible with a print statement.
使用 Stringio 阅读
一旦我们将一些数据写入 StringIO 缓冲器,我们也可以读取它,让我们看看一个代码片段:
1import io
2
3input = io.StringIO('This goes into the read buffer.')
4print(input.read())
Let's see the output for this program:
使用 StringIO 读取文件
还可以读到一个文件并通过网络作为Bytes流。 io模块可以用来转换像图像这样的媒体文件,以转换为Bytes。
1import io
2
3file = io.open("whale.png", "rb", buffering = 0)
4print(file.read())
Let's see the output for this program: For this program to run, we had a whale.png image present in our current directory.
開啟( ) vs 開啟( )
io.open()
函数是执行 I/O 操作的最受欢迎的方式,因为它是作为一个高级别接口来 peform 文件 I/O. 它将 OS 级的文件描述器包裹在一个对象中,我们可以用来以 Pythonic 方式访问文件。 os.open()
函数负责较低级别的 POSIX syscall。 它采用了基于 POSIX 的输入参数,并返回了一个代表已打开的文件的文件描述器。 它不会返回文件对象;返回的值不会有read()
或write()
函数。 总体而言,io.open()
函数只是一个over.open()
函数的包裹。 `os
结论
在本课中,我们研究了 python IO 模块的简单操作,以及我们如何使用 BytesIO 来管理 Unicode 字符,但是,如果您正在寻找完整的文件操作,如删除和复制文件,请阅读 python 阅读文件。