为了方便文件操作的学习,写一个缓存的小工具再合适不过了,再加上对Linux内部文件系统的一些原理性的学习,做到熟练应用感觉问题不大,只是时间问题,先上代码。
#!/usr/bin/python3
import functools
import json
import os
import time
from collections import OrderedDict
d=OrderedDict()
def dcache():
with open('1.txt','r+') as f:
if not f.read():
d={}
else:
f.seek(0)
d=json.loads(f.read())
return d
d=dcache()
def cache(fn):
@functools.wraps(fn)
def wrapper(*args):
if str(args) in d.keys():
return d[str(args)]
else:
d[str(args)]=fn(*args)
string=json.dumps(d)
with open('1.txt','r+') as f:
f.write(string)
return fn(*args)
return wrapper
@cache
def add(x,y,z=1):
time.sleep(z)
return x+y
print(add(2,3))
print(add(1,1))
因为最近才学了装饰器,所以能用到的地方当然要用,要做一个缓存,我首先就想到了存储数据的格式就应该用字典,利用K,V对可以很方便的查找相对应的参数和值,并且要用有序字典,这样在每次调用程序时才不会出现错误。
文件的读写操作没什么好说的,最好还是用with open,已经封装的很好了,用起来很方便。
最后是要注意的地方,就是写数据时,要将字典序列化后再写入,写入磁盘,再从磁盘读取到内存中时,都要序列化成二进制的字符串才行,机器可不认识高级语言,它只认识0、1数字和电信号,这样子存进去的数据在读入时也要反序列化才行。序列化和反序列化在Python里已经被封装的非常好了,直接调用函数就行,非常方便。