第三周 Day 5 —— Python数据持久化
一、数据持久化
1. 文件上下文
with open() as 文件对象:
文件上下文(可以操作文件的位置)
with open('./test.txt', encoding='utf-8') as f:
f.read()
f.read()
# f.read() #ValueError: I/O operation on closed file.
2. 数据持久化方法
数据持久化需要做到一下3点:
-
创建文件保存需要持久化的数据
-
在程序中每次需要这个数据,不直接赋值,而是从文件中去读取它的值
-
在程序中如果修改了这个数据的值,需要将这个最新的值更新到文件中
在程序中用一个数据来保存当前程序启动的次数,并且打印次数
# 1. 获取上一次运行时对应的次数
with open('../file/test.txt', encoding='utf-8') as f:
num = int(f.read())
num += 1
print(num)
# 2. 写入新数据
with open('../file/test.txt', 'w', encoding='utf-8') as f:
f.write(str(num))
练习2:写程序录入学生的成绩,每次录入成绩的时候以’q‘结束
with open('../file/score.txt', encoding='utf-8') as f:
content = f.read()
scores = eval(content)
print(scores)
while True:
score = input('请输入学生的成绩(q结束):')
if score != 'q':
scores.append(score)
else:
break
print(scores)
with open('../file/score.txt', 'w', encoding='utf-8') as f:
f.write(str(scores))
练习2:写程序录入学生信息,录入内容:姓名和电话。要求每次在录入的时候保留上次录入的结果