一、扁平文件
scores = [88, 99, 77, 55]
def write_scores():
with open('datafile.txt', 'w', encoding = 'utf8') as f: #文件仅含一个列表
f.write(str(scores))
print('文件写入完成...')
def read_scores():
with open('datafile.txt', 'r', encoding='utf8') as f:
lst = eval(f.read()) #转换数据类型
lst[0] = 99
print(lst)
if __name__ == '__main__':
#write_scores() #先运行写入函数
read_scores()
[99, 99, 77, 55]
二、pickle
1、序列化为字符串
- 将对象序列化为字符串 pickle.dumps(obj)
- 从字符串反序列化为对象 pickle.loads(s)
import pickle
person = {'name':'Tom', 'age':20}
s = pickle.dumps(person) #把任意类型对象序列化成字符串
s
p = pickle.loads(s) #反向转换
p
b'x80x03}qx00(Xx04x00x00x00nameqx01Xx03x00x00x00Tomqx02Xx03x00x00x00ageqx03Kx14u.'
{'name': 'Tom', 'age': 20}
2、序列化对象到文件
- 对象序列化为文件 pickle.dump(obj, file)
- 文件反序列化为对象 pickle.load(file)
pickle.dump(person, open('pickle_db', 'wb'))
p = pickle.load(open('pickle_db', 'rb'))
p
type(p)
{'name': 'Tom', 'age': 20}
dict
三、shelve
- .open('dbfile')
- .close()
- db['key']=obj
- len(db)
import shelve
scores = [99, 88, 77]
student = {'name':'Mike', 'age':20}
db = shelve.open('shelve_student') #创建数据库文件
db['s'] = student
db['scores'] = scores
len(db) #有两个键值
temp_student = db['s']
temp_student
type(temp_student)
2
{'name': 'Mike', 'age': 20}
dict
del db['scores']
len(db)
1
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
def write_shelve():
s = Student('Yom', 20)
db = shelve.open('shelve_student_db')
db['s'] = s
db.close()
def read_shelve():
db = shelve.open('shelve_student_db')
st = db['s']
print(st)
print(st.name)
print(st.age)
db.close()
if __name__ == '__main__':
#write_shelve() #先写入再读取
read_shelve()
Yom
Yom
20