前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python IO编程

Python IO编程

作者头像
keinYe
发布2019-08-01 11:06:44
5360
发布2019-08-01 11:06:44
举报
文章被收录于专栏:keinYekeinYe

IO 在编程语言中特指输入和输出「即 input 和 output」。在 IO 编程中 stream (流)是一个重要的概念,一个完整的 IO 操作通常含有 input 和 output 两个数据流,我们称之为输入流和输出流。

由于 CPU 和内存的速度远远超过外设的速度,因此 IO 操作通常分为同步和异步两种方式,我们生活中所使用的操作系统通常情况下设计到 IO 操作的均使用的是异步 IO。那么同步 IO 和异步 IO 的区别是什么

  1. 同步 IO:即在遇到外设读取数据时,CPU 停止后续代码的执行,等待 IO 读取完成在接着执行剩余的代码。
  2. 异步 IO:即在遇到外设读取数据时,CPU 继续执行其他的代码,待 IO 读取完成在返回处理相关数据。

同步 IO 和异步 IO 最大的区别在遇到外设长时间读取数据时,CPU 是否等待 IO 的执行结果。

异步 IO 的性能远远高于同步 IO,但异步 IO 的复杂度远远高于同步 IO。操作 IO 的能力都是由操作系统提供的,每一种编程语言都会讲操作系统提供的接口进行封装以方便使用。

在 python 中常用的 IO 操作有文件读写、内存读写等。

文件读写

文件的读写是最常用的操作,Python 中内置了操作文件的函数,在使用方法上与 C 语言是兼容的。在现代操作系统上读写文件的功能都是由操作系统提供的,Python 中的文件读写实际上是对操作系统提供的一个文件对象的读写。

在 Python 中操作文件的函数主要有打开文件、读文件、写文件、关闭文件。 打开文件的函数如下:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
   Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

open 函数的 mode 的设置值有以下几种

Character

Meaning

'r'

open for reading (default)

'w'

open for writing, truncating the file first

'x'

open for exclusive creation, failing if the file already exists

'a'

open for writing, appending to the end of the file if it exists

'b'

binary mode

't'

text mode (default)

'+'

open a disk file for updating (reading and writing)

'U'

universal newlines mode (deprecated)

读文件的函数如下:

os.read(fd, n)
   Read at most n bytes from file descriptor fd.   Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.

写文件的函数如下:

os.write(fd, str)
   Write the bytestring in str to file descriptor fd.   Return the number of bytes actually written.

关闭文件的函数如下:

fileinput.close()
   Close the sequence.   The class which implements the sequence behavior provided by the module is available for subclassing as well:

在对一个文件进行操作之前,必须先使用打开文件,以获取文件对象。下面是一个完整的文件读写程序

#!/usr/bin/env python3#-*- coding:utf-8 -*-f = open('test', 'w+')
f.write('hello world!')
print(f.read())
f.close()

以上代码在运行时没有任何的输出,这是由于使用 open 函数的 mode 参数仅仅设置为写模式,让我们对以上代码进行修改在进行运行

#!/usr/bin/env python3#-*- coding:utf-8 -*-f = open('test', 'w')
f.write('hello world!')
f.close()
f = open('test', 'r')
print(f.read())
f.close()

此时在次运行上面的代码,我们可以看到控制台输出了hello world!。

文件读写的过程中不可避免的会出现 IOError, 当出现错误后面的代码就不会执行,如果按我们以上的代码执行,不可避免的会造成文件没有正常关闭会使系统重复生成文件对象浪费资源,为了保证能够正常关闭文件,我们可以使用 try...finally 来实现。我们将以上代码进行修改如下

#!/usr/bin/env python3#-*- coding:utf-8 -*-try:
   f = open('test', 'w')
   f.write('hello world!')finally:    if f:
       f.close()try:
   f = open('test', 'r')
   print(f.read())finally:    if f:
       f.close()

以上代码虽然解决了文件不能正常关闭的问题,但是我们却为此编写了大量的 try...finally 代码,看起来也不是很美观,没关系,python 为我们准备 with 关键字来解决以上问题,

#!/usr/bin/env python3#-*- coding:utf-8 -*-with open('test', 'w') as f:
   f.write('hello world!')with open('test', 'r') as f:
   print(f.read())

现在看起来是不好多了。

内存读写

python 通过 StringIO 和 BytesIO 来读写内存中的数据。StringIO 顾名思义就是读写内存中的字符串。BytesIO 用来读写内存中的二进制数据。

以下是 StringIO 的简单实用示例

#!/usr/bin/env python3#-*- coding:utf-8 -*-import iof = io.StringIO()
f.write("hello world!")
print(f.getvalue())

以下是 BytesIO 的简单实用示例

#!/usr/bin/env python3#-*- coding:utf-8 -*-import iof = io.BytesIO()
f.write('keinYe')
print(f.getvalue())
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-01-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 keinYe 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文件读写
  • 内存读写
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档