day014.数据持久化

回顾

import random–产生随机整数模块

# 1.产生随机小数(0~1, 1取不到)
print(random.random())   # (0, 1)
print(random.random() * 20)   # (0, 20)产生0到20的随机数
print(random.random() * 10 + 10)    # (10, 20)产生10到20的随机数

# 2.随机打乱列表中的元素(洗牌)
nums = list(range(1, 10))
print(nums)
random.shuffle(nums)
print(nums)

# 3.随机获取元素
nums = list(range(1, 10))
print(random.choice(nums))
print(random.choices(nums, k=3))

nums = [1, 2, 3, 4]
# 权重值是0表示不取,权重越大,取值机会越大
print(random.choices(nums, [1, 0, 1, 0], k=1))

nums = [1, 2, 3, 4]
print(random.choices(nums, [1, 1, 4, 1]))

1,数据持久化

# 1.文件上下文
"""
with open() as 文件对象:
    文件上下文(可以操作文件的位置)
"""
with open('./合同', encoding='utf-8') as f:
    f.read()
    f.read()

数据持久化的方法
数据持久化需要做到以下3点:
1)创建文件保存需要持久数据;
2)在程序中每次需要这个数据,不直接赋值而是从文件中去读取它的值;
3)在程序如果修改了这个数据的值,需要将这个最新的值更新到文件中。

# 练习1:在程序中用一个数据来保存当前程序启动的次数,并且打印次数
# 1 - 获取上一次运行时对应的次数
with open('files/count.txt', encoding='utf-8') as f:
    num = int(f.read())
    num += 1
    print(num)

with open('files/count.txt', 'w', encoding='utf-8') as f:
    f.write(str(num))
    
# 练习2:写程序录入学生的成绩,每次录入成绩的时候以'q'结束
scores = []
with open('files/score.txt', encoding='utf-8') as f:
    content = f.read()   # '[]', '[45, 67, 98]'
    scores = eval(content)   # [], [45, 67, 98]
while True:
    score = input('请输入学生的成绩(q退出):')
    if score == 'q':
        break
    scores.append(float(score))

print(scores)
with open('files/score.txt', 'w', encoding='utf-8') as f:
    f.write(str(scores))   # '[45, 67, 98]', '[45, 67, 98, 100]'
    
# 练习3:写程序录入学生信息,录入内容:姓名和电话。要求每次在录入的时候保留上次录入的结果

with open('files/students', encoding='utf-8') as f:
    content = f.read()
    students = eval(content)
while True:
    name = input('姓名:')
    tel = input('请输入电话:')
    students[name] = tel
    value = input('继续or退出(y/n):')
    if value == 'n':
        break

print(students)

with open('files/students', 'w', encoding='utf-8') as f:
    f.write(str(students))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值