python笔记-012-文件和异常

来源:互联网 发布:哈扎尔辞典 知乎 编辑:程序博客网 时间:2024/06/06 11:36
# 打开文件# 读取模式 ('r')、写入模式 ('w')# 附加模式 ('a')、读取和写入文件的模式('r+')import jsonwith open("pi_digits.txt", 'r+') as file_object:    # 读取文件    '''    contents = file_object.read()    print(contents)    print('======')    '''    # 逐行读取    '''    for line in file_object:        print(line.rstrip())    '''    # 保存文件各行到列表    '''        lines = file_object.readlines()    for line in lines:        print(line.rstrip())    '''    # 写入文件    file_object.write('this is a test...\n')# 异常print("Give me two numbers, and I'll divide 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 ZeroDivisionError:        print("You can't divide by 0!")    else:        print(answer)# 存储数据:json# 写'''numbers = [2, 3, 5, 7, 11, 13]filename = 'numbers.json'with open(filename, 'w') as f_obj:    json.dump(numbers, f_obj)'''# 读filename = 'numbers.json'with open(filename) as f_obj:    numbers = json.load(f_obj)print(numbers)

原创粉丝点击