【Python】[IO编程]文件读写,StringIO和BytesIO,操作文件和目录,序列化

IO在计算机中指Input/Output,也就是输入和输出。

1、文件读写,

1,读文件【使用Python内置函数,open,传入文件名标示符】

>>> f = open('/Users/michael/test.txt', 'r')

标示符‘r’代表 读。

如果文件打开成功,调用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用

一个str对象表示:

>>> f.read()
'Hello, world!'

最后文件读取完毕调用 close 关闭文件

2,

try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()
另一种try catch
with open('/path/to/file', 'r') as f:
    print(f.read())

3,StringIO就是在内存中创建的file-like Object,常用作临时缓冲。

4,二进制文件:

读取二进制文件时,只需修改 标示符为 ‘rb’

5,字符编码

读取非UTF-8编码的文件,只需open 传入参数 encoding='gbk'

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()

'测试'

编码太乱可以选择直接忽略

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')

6,写文件

只是修改 标示符 ‘r’,‘rb’ 为 'w','wb'

with语句操作文件【因为try那种太繁琐了】

with open('文件路径名','w',encoding='gbk') as f:
    f.write('你好!')

2、StringIO和BytesIO

1,StringIO 内存中读写str

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5

2,BytesIO顾名思义读写字节的操作在内存

StringIO和BytesIO操作内存中的str和bytes,使用相同的接口。

3、操作系统文件和目录

>>>import os
>>>os.name
'posix'//linux
'nt'   //windows
>>>os.uname()

//更详细的操作系统信息

操作文件和目录,查看,创建,删除,

目录很文件的分割, os.path.split('文件路径/a.txt')

4、序列化

内存到硬盘。

对象到字节。

dict转JSON【json.dumps(d)】

>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'

JSON转dict【json.loads(json_str)】

>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}

注意,如果要把自定义类装换为JSON需要定义个函数

def student2dict(std):
    return {
        'name': std.name,
        'age': std.age,
        'score': std.score
    }