1、文件读写
python的文件读写非常简单
with open(file,'r',errors='ignore') as f:
print(f.open())
with open(file,'w',errros='ignore') as f:
f.write("111")
with open(file,'a',errors='ignore') as f:
f.write("qww")
2、StringIo与ByteIo
from io import StringIO
f=StringIO()
f.write("hello world!")
print(f.getvalue())
f=StringIO("hello world!")
print(f.read())
f.close()
f=io.BytesIO();
f.write("农夫山泉".encode("utf-8"))
print(f.getvalue())
f=io.BytesIO("农夫山泉".encode("utf-8"))
print(f.getvalue())
3、序列化存储
对于生产的实例化对象,可以用json模块转化存储
#转化为json
import json
d=dict(name="mike",age=20)
json.dumps(d)
#从json中读取字典
import json
d=dict(name="mike",age=20)
jumps=json.dumps(d)
>>json.loads(jumps)
目前只对于dict有效,对于类或者实例对象,需要补上一个default或者object_hook
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s=Student("mike",20,89)
print(json.dumps(s,default=lambda obj:obj.__dict__))
反实例化需要object_hook
json_jump=json.dumps(s,default=lambda obj:obj.__dict__)
print(json.loads(json_jump,object_hook=lambda d:Student(d['name'],d['age'],d['score'])))