2.4. IO编程

2.4.1. 文件读写

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
with open('./out.log','r',encoding='utf-8',errors='ignore') as f:
    print(f.read())

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

2.4.2. StringIO和BytesIO

内存中读取str或者byte

from io import StringIO
f = StringIO()
f.write('hello')
f.write(" ")
f.write("world!")
print(f.getvalue())

from io import BytesIO
f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
f.read()

2.4.3. 操作文件和目录

核心是2个模块, 一个是os模块,一个是os.path模块

import os
# 绝对路径
os.path.abspath(".")
# 目录拼接
os.path.join("/","etc")
os.mkdir("/tmp/a.txt")
os.rmdir("/tmp/a.txt")
# 拆分路径
os.path.split
# 拆分扩展
os.path.splitext

2.4.4. 序列化