数据持久化
写一个程序,统计这个程序启动次数
a. 数据保存在文件中
b. 需要数据的时候从文件中去读数据
c. 当数据发生改变的时候,对保存的数据的文件进行更新
注意:如果以读的方式打开一个不存在的文件,会报错,如果以写的方式打开一个不存在的文件,不会报错,会新建一个文件
with open(r'.\file\a.txt',encoding='utf-8') as f:
count = int(f.read())
count += 1
print(count)
with open(r'.\file\a.txt','w',encoding='utf-8') as f:
f.write(str(count))
写程序实现添加学生的功能,每次运行程序添加的学生,下次还在
with open(r'.\file\student.txt','a',encoding='utf-8') as f:
name = input('请输入名字:')
age = int(input('请输入年龄:'))
tel = input('请输入电话:')
f.write(name + '')
# f.write(str(age))
# f.write(tel)
with open(r'.\file\student.txt',encoding='utf-8') as f:
content = f.readlines()
print(content)