Python第五周第二次作业

学习文件的处理  

10-1 学习笔记

创建一个名为note的txt文档

with open('note.txt') as fil:
    context = fil.read()
print(context)
print()
    
with open('note.txt') as fil:
    for line in fil:
        print(line.strip())
print()

with open('note.txt') as fil:
    lines = fil.readlines()
for line in lines:
    print(line.strip())

readlines()为一个包含每行内容的列表,而readline()为一个包含一行中每个字符的列表,重复使用就能逐行遍历

10-6 加法运算

有了异常处理,就可以解决文本转数字失败的情况了

while True:
    print("Enter 'q' to quit!")
    first_num = input("Please input the first number:")
    if(first_num == 'q'):
        break
    try:
        first_num = int(first_num)
    except ValueError:
        print("The number is wrong!")
    else:
        second_num = input("Please input the second number:")
        if(second_num == 'q'):
            break
        try:
            second_num = int(second_num)
        except ValueError:
            print("The number is wrong!")
        else:
            print(first_num + second_num)

10-12 记住喜欢的数字

json似乎不能当作文档一样储存多次内容?因此我只好将之前储存过的内容提出来,将新加的内容接到后面……

import json

def show_num():
    print("Your favorite numbers:", end = '')
    try:
        with open('number.json') as fil:
            numbers = json.load(fil)
            print(numbers)
    except FileNotFoundError:
        print("None")

def get_num():
    try:
        with open('number.json') as fil:
            numbers = json.load(fil)
    except FileNotFoundError:
        numbers = ''
    numbers += input("Please input your favorite number:")
    numbers += ' '
    with open('number.json', 'w') as fil:
        json.dump(numbers, fil)

def favo_num():
    show_num()
    get_num()
    show_num()
    print("")

favo_num()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值