python 文件和异常处理

时间:2021-03-30 00:46:20
#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))