【廖雪峰老师python教程】——IO编程

  • 同步IO
  • 异步IO

最常见的IO——读写文件


  • 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。
  • open()
  • read()
  • close()
try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()
  • with【保证了错误也能关闭】
with open('/path/to/file', 'r') as f:
    print(f.read())
  • read()、read(size)、readline(),readiness()四者使用的区别
  • 还有一些具体的读写编码方式,日后自己复习。

StringIO和BytesIO


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from io import StringIO

# write to StringIO:
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
print(f.getvalue())

# read from StringIO:
f = StringIO('水面细风生,\n菱歌慢慢声。\n客亭临小市,\n灯火夜妆明。')
while True:
    s = f.readline()
    if s == '':
        break
    print(s.strip())
!/usr/bin/env python3
# -*- coding: utf-8 -*-

from io import BytesIO

# write to BytesIO:
f = BytesIO()
f.write(b'hello')
f.write(b' ')
f.write(b'world!')
print(f.getvalue())

# read from BytesIO:
data = '人闲桂花落,夜静春山空。月出惊山鸟,时鸣春涧中。'.encode('utf-8')
f = BytesIO(data)
print(f.read())

操作文件和目录


  • os模块【直接调用操作系统提供的接口函数】

系列化


  • 内存到磁盘的文件存储pickle模块
  • py和js的转换序列化json模块
  • Python语言特定的序列化模块是pickle,但如果要把序列化搞得更通用、更符合Web标准,就可以使用json模块。

    json模块的dumps()loads()函数是定义得非常好的接口的典范。当我们使用时,只需要传入一个必须的参数。但是,当默认的序列化或反序列机制不满足我们的要求时,我们又可以传入更多的参数来定制序列化或反序列化的规则,既做到了接口简单易用,又做到了充分的扩展性和灵活性。




 

猜你喜欢

转载自www.cnblogs.com/ChaoyuanJam/p/9749188.html
今日推荐