1.保存数据到文件
文本文件可以存储有类型的对象,但是过程比较繁琐,因为所有类型都会转换为字符串。将存储在文件中的少部分有类型的对象读取出来的时候,可以用
eval(f.read())
注意,若直接读,结果为字符串格式。
// An highlighted block
scores = [88, 99, 77, 55]
def write_scores():
with open('datalist.txt', 'w', encoding='utf8') as f:
f.write(str(scores))
/// f.read()出来的是字符串'[88, 99, 77, 55]',要想还原回列表,用eval(f.read())
def read_scores():
with open('datalist.txt', 'r', encoding='utf8') as f:
lst = eval(f.read())
lst[1] = 99
print(lst)
if __name__ == '__main__':
# write_scores()
read_scores()
;
2.pickle
为存取方便,引入pickle模块进行读写操作。
写操作
1.创建.pkl文件,‘wb’,二进制写入
2.pickle.dump(obj,file),将对象存入文件
读操作
1.打开.pkl文件,‘wr’,二进制读取
2.obj = pickle.load(file),将对象读出来
///字典表用pickle方式存取
import pickle
person = {'name': 'cj', 'age': 24}
def dump_file():
with open('datalist.pkl', 'wb') as f:
pickle.dump(person, f)
def load_file():
with open('datalist.pkl','rb') as f:
dict1 = pickle.load(f)
print(dict1)
if __name__ == '__main__':
dump_file()
load_file()
3. shelve模块
如果将多个对象存储到一个文件里,反序列化时,会把所有的对象都取出来,但可能你只想取出其中特定的对象。为此我们引入shelve。当然我们也可以通过把不同的对象dump到不同的文件来解决。但维护麻烦。
写操作
1.创建文件,用db=shelve.open(file)创建
2.存入对象,db[‘key1’]=obj1, db[‘key2’]=obj2
3.关闭文件,db.close()
读操作
1.打开文件,db=shelve.open(file)打开
2,读取对象,obj1=db[‘key1’], obj2=db[‘key2’]
3.关闭文件,db.close()
// 把类实例对象用shelve存取
import shelve
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def running(self):
print('studeng {} is running'.format(self.name))
def write_shelve():
s = Student('CJ', 24)
db=shelve.open('shelve_student_db')
db['s']=s
db.close()
def read_shelve():
db = shelve.open('shelve_student_db')
s=db['s']或s=db.get('s')
print(s)
print(s.name)
db.close()
if __name__ == '__main__':
write_shelve()
read_shelve()