(一)扁平文件
scores = [88,99,77,55]
def write_scores():
with open('date_list.txt','w',encoding='utf8') as f:
f.write(str(scores))
print('文件写入成功
def read_scores():
with open('date_list.txt','r',encoding='utf8') as f:
list = eval(f.read())
list[0] = 87
print(list)
if __name__ == '__main__':
write_scores()
read_scores()
----------------------------------------
文件写入成功!
[87, 99, 77, 55]
(二)pickle
>>> import pickle
>>> person = {'name':'Tom','age':20}
>>> s = pickle.dumps(person)
>>> s
b'x80x03}qx00(Xx04x00x00x00nameqx01Xx03x00x00x00Tomqx02Xx03x00x00x00ageqx03Kx14u.'
>>> p = pickle.loads(s)
>>> p
{'name': 'Tom', 'age': 20}
>>> pickle.dump(person,open('pickle_dump','wb'))
>>> p = pickle.load(open('pickle_dump','rb'))
>>> p
{'name': 'Tom', 'age': 20}
(三)shelve
import shelve
# scores = [99,88,77]
# student = {'name':'Tom','age':20}
# db = shelve.open('shelve_student')
# db['s'] = student
# db['scores'] = scores
# print(len(db))
db = shelve.open('shelve_student')
stu = db['s']
print(stu)
scores = db['scores']
print(scores)
#删除
del db['s']
db.close()