當(dāng)前位置:首頁(yè) > IT技術(shù) > 編程語(yǔ)言 > 正文

Python文件和異常(五)
2022-09-06 22:57:37

一、從文件中讀取數(shù)據(jù)

open()函數(shù)

參數(shù)

  • file 文件路徑
  • mode
mode參數(shù) 可做操作 若文件不存在 如何處理原內(nèi)容
r 只可讀 報(bào)錯(cuò) -
r+ 可讀可寫 報(bào)錯(cuò)
w 只可寫 創(chuàng)建
w+ 可讀可寫 創(chuàng)建
a 只可寫 創(chuàng)建 否,追加
a+ 可讀可寫 創(chuàng)建 否,追加
x 只可寫 創(chuàng)建 -
x+ 可讀可寫 創(chuàng)建 -
# 一
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')

三、追加到文件

如果文件存在則在原文件內(nèi)容后寫入,如果不存在則創(chuàng)建寫入

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代碼塊成功執(zhí)行的代碼都放在else代碼塊中

print('請(qǐng)輸入兩個(gè)數(shù)');
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)

五、數(shù)據(jù)存儲(chǔ)

json.dump()

  • 參數(shù)
    • 存儲(chǔ)的數(shù)據(jù)
    • 存儲(chǔ)數(shù)據(jù)的文件對(duì)象

json.load()

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

#讀取json格式數(shù)據(jù)
with open(fileName) as f:
    nums = json.load(f)
print(nums)

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

開通會(huì)員,享受整站包年服務(wù)立即開通 >