Day 14 数据持久化
1.文件上下文
with open( ) as 文件对象:
文件上下文(可以操作文件的位置)
with open('./合同') as f:
f.read()
f.read()
# 离开文件上下文之后文件会自动关闭
2.数据持久化的方法
数据持久化需要做到以下三点
1)创建文件保存需要持久的数据
2)在程序中每次需要这个数据,不直接赋值而是从文件中去读取它的值
3)在程序中如果修改这个数据的值,需要这个最新的值更新到文件中
# 练习:在程序中用一个数据来保存当前程序启动的次数,并且打印次数
# 1.获取上一次运行时对应的值
witn open('files/文件名.txt',encoding = 'utf-8')as f:
num = int(f.read())
num += 1
print(num # 运行第一次
with open('files/count','w',encoding='utf-8')as f:
f.write(str(num)) # 再打开
# 练习2:写程序录入学生的成绩,每次录入成绩的时候以'q'结束
with open('./score.txt', encoding='utf-8') as f:
content = f.read() # scores = []
scores = eval(content)
while True:
score = input('请输入学生成绩(q推出):')
if score == 'q':
break
scores.append(int(score))
print(scores)
with open('./score.txt', 'w', encoding='utf-8')as f:
f.write(str(scores))
# 练习# 练习3:写程序录入学生信息,录入内容:姓名和电话。要求每次在录入的时候保留上次录入的结果
"""
姓名:
电话:
继续or退出(y/n:)y
姓名:
电话:
继续or退出(y/n:)y
姓名:
电话:
继续or退出(y/n:)n
{姓名1:电话1, 姓名2:电话2,...}
程序结束!
with open('./score.txt', encoding='utf-8') as n:
content = n.read()
students = eval(content)s
while True:
students_name = input('姓名:')
students_num = input('电话:')
students[students_name] = students_num
choice = input('继续or退出(y/n)')
if choice == 'y':
continue
elif choice == 'n':
break
print(str(students))
with open('./score.txt', 'w', encoding='utf-8') as n:
n.write(str(students))