python 文件和异常处理

#10-1 python学习笔记
with open("learnpy.txt") as file_pro:
    contents = file_pro.read()
    print(contents)
with open("learnpy.txt") as file_pro:
    for line in file_pro:
        print(line)
with open("learnpy.txt") as file_pro:
    lines = file_pro.readlines()
for line in lines:
    print(line)

#10-2 replace python with c
for line in lines:
    print(line.replace('Python','c'))

#10-3 写入文件
print("please input your name")
user_name = input()
with open("guest.txt",'w') as file_ob:
    file_ob.write(user_name)

#10-4 向文件中添加用户
while True:
    message = input("please input your name")
    if(message == 'quit'):
        break
    print("hello"+" "+message)
    with open('guest_list.txt', 'a') as file_object:
        file_object.write(message+'\n')

#10-7 加法计算器
print("Give me two numbers, and I'll add them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) + int(second_number)
    except ValueError:
        print("illegal input")
    else:
        print(answer)


#10-8 猫和狗
def printFile(file_name):
    try:
        with open(file_name) as file_ob:
            print(file_ob.read())
    except FileNotFoundError:
          msg = file_name + " does not exist."
          print(msg)
printFile("cats.txt")
printFile("dogs.txt")
printFile("cat.txt")

#10-9 猫和狗,文件不存在程序沉默
def printFile2(file_name):
    try:
        with open(file_name) as file_ob:
            print(file_ob.read())
    except FileNotFoundError:
          pass
printFile2("cats.txt")
printFile2("dogs.txt")
printFile2("cat.txt")

#10-11 喜欢的数字
import json
love = input("input your luck number")
with open("json.txt",'w') as file_ob:
    json.dump(love,file_ob)
with open("json.txt") as file_ob:
    print("you love number "+ json.load(file_ob))



   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值