• <dd id="weawc"></dd>
  • Python文件和異常(五)
    2022-09-06 22:57:37

    一、從文件中讀取數據

    open()函數

    參數

    • file 文件路徑
    • mode
    mode參數 可做操作 若文件不存在 如何處理原內容
    r 只可讀 報錯 -
    r+ 可讀可寫 報錯
    w 只可寫 創建
    w+ 可讀可寫 創建
    a 只可寫 創建 否,追加
    a+ 可讀可寫 創建 否,追加
    x 只可寫 創建 -
    x+ 可讀可寫 創建 -
    # 一
    f = open('pi.txt','r',encoding='utf-8')
    contents = f.read()
    print(contents)
    
    #二
    with open('pi.txt') as line:
        content = line.read()
        # print(content)
        # rstrip()方法剔除字符串末尾空白
        print(content.rstrip())
    

    1、逐行讀取

    with open('pi.txt') as f:
        for line in f:
            print(line.rstrip())
    

    2、讀取文件以列表格式返回

    lines = []
    with open('pi.txt') as f:
       lines = f.readlines()·
    print(lines)
    

    二、寫入文件

    with open('a.txt','w',encoding='utf-8') as f:
        f.write('i like')
    

    三、追加到文件

    如果文件存在則在原文件內容后寫入,如果不存在則創建寫入

    with open('a.txt','a',encoding='utf-8') as f:
        f.write('hello word')
    

    四、異常

    1、處理ZeroDivisionError異常

    try-except代碼塊

    try:
        print(2/0)
    except ZeroDivisionError:
        print('by zero')
    

    2、else代碼塊

    try-except-else

    依賴于try代碼塊成功執行的代碼都放在else代碼塊中

    print('請輸入兩個數');
    print('enter q to quit');
    while True:
        firstNum = input('first num')
        if(firstNum=='q'):
            break
        secondNum = input('second num')
        if(secondNum =='q'):
            break
        try:
            result = int(firstNum)/int(secondNum)
        except ZeroDivisionError:
            print('can not')
        else:
            print(result)
    

    五、數據存儲

    json.dump()

    • 參數
      • 存儲的數據
      • 存儲數據的文件對象

    json.load()

    • 參數
      • 文件
    import json
    # fileName = 'nums.json'
    # 存儲json格式數據
    # nums= [1,2,2,3,4,5,6]
    # with open(fileName,'w',encoding='utf-8') as f:
    #     json.dump(nums,f)
    
    #讀取json格式數據
    with open(fileName) as f:
        nums = json.load(f)
    print(nums)
    

    本文摘自 :https://www.cnblogs.com/


    更多科技新聞 ......

    日本成人三级A片
  • <dd id="weawc"></dd>