Python编程作业【第五周】(二)

本文通过具体实例介绍了Python文件操作的基本方法,包括读取文件内容、替换字符串并输出、记录来宾姓名及原因等,并实现了简单的加法计算器功能,还探讨了异常处理的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10-1 Python notes

file_path = "learning_python.txt"
with open(file_path) as obj:
    str1 = obj.read()
print(str1)
with open(file_path) as obj:
    for line in obj.readlines():
        print (line)
with open(file_path) as obj:
    str3 = obj.readlines()
print(str3)

10-2 C notes

file_path = "learning_python.txt"
with open(file_path) as obj:
    str1 = obj.read()
print(str1.replace("python", "C"))

10-3 guests

file_path = "guest.txt"
guest = input("Please input the guest name: ")
with open(file_path, 'w') as obj:
    obj.write(guest)

10-4 guests list

file_path = "guest.txt"
with open(file_path, 'w') as obj:
    while True:
        guest = input("Please input the guest name: ")
        if guest == "q": break
        obj.write(guest + "\n")

10-5 survey of programming

file_path = "guest.txt"
with open(file_path, 'w') as obj:
    while True:
        guest = input("Please input the reason why you love programming: ")
        if guest == "q": break
        obj.write(guest + "\n")

10-6 addition calculator

try:
    num1 = input("Please input the first number: ")
    num2 = input("Please input the second number: ")
    print(int(num1) + int(num2))
except (ValueError):
    print("Sorry, you cannot input a string.")

10-7 additioner

while True:
    try:
        num1 = input("Please input the first number: ")
        num2 = input("Please input the second number: ")
        res = int(num1) + int(num2)
    except (ValueError):
        print("Sorry, you cannot input a string.")
        continue
    else: 
        print(res)
        break

10-8 cats and dogs

try:
    with open("cats.txt") as obj:
        for line in obj.readlines(): print(line)
    with open("dogs.txt") as obj:
        for line in obj.readlines(): print(line)
except FileNotFoundError:
    print("This file doesn't exist.")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值