1. 程式人生 > 程式設計 >詳解python中的異常和檔案讀寫

詳解python中的異常和檔案讀寫

Python異常

1、python異常的完整語法

try:
  # 提示使用者輸入一個整數
  num = int(input("輸入一個整數:"))
  # 使用 8 除以使用者輸入的整數並且輸出
  result = 8 / num
  print(result)
except ValueError:
  print("請輸入正確的整數!")
except Exception as result:
  print("未知錯誤:%s" % result)
else:
  print("嘗試成功")
finally:
  print("無論是否出現錯誤都會執行的程式碼!")
print("-" * 50)

2、python異常的傳遞性

當函式/方法執行出現異常,會將異常傳遞給函式/方法的呼叫一方,如果傳遞到主程式,仍然沒有異常處理,程式才會被終止。

# 異常的傳遞性
def demo1():
  return int(input("輸入整數:"))


def demo2():
  return demo1()
# 利用異常的傳遞性,在主程式捕獲異常


try:
  print(demo2())
except Exception as result:
  print("未知錯誤:%s" % result)

3、python主動丟擲異常

def input_password():
  # 1. 提示使用者輸入密碼
  pwd = input("請輸入密碼:")
  # 2. 判斷密碼長度 >= 8,返回使用者輸入的密碼
  if len(pwd) >= 8:
    return pwd
  # 3. 如果 < 8 主動丟擲異常
  print("主動丟擲異常!")
  # 1> 建立異常物件 - 可以使用錯誤資訊字串作為引數
  ex = Exception("密碼長度不夠!")
  # 2> 主動丟擲異常
  raise ex


# 提示使用者輸入密碼
try:
  print(input_password())
except Exception as result:
  print(result)

Python檔案讀寫

1、讀取檔案後文件指標會改變

# 1. 開啟檔案
file = open("test.py")
# 2. 讀取檔案內容
text = file.read()
print(text)
print(len(text))
print("-" * 50)
text = file.read()
print(text)
print(len(text))
# 3. 關閉檔案
file.close()

2、複製小檔案寫法

# 1. 開啟
file_read = open("test.py")
file_write = open("test[復件].py","w")
# 2. 讀、寫
text = file_read.read()
file_write.write(text)
# 3. 關閉
file_read.close()
file_write.close()

3、複製大檔案寫法

# 1. 開啟
file_read = open("test.py")
file_write = open("test[復件].py","w")
# 2. 讀、寫
while True:
  # 讀取一行內容
  text = file_read.readline()
  # 判斷是否讀取到內容
  if not text:
    break
  file_write.write(text)

# 3. 關閉
file_read.close()
file_write.close()

以上就是詳解python中的異常和檔案讀寫的詳細內容,更多關於python 異常和檔案讀寫的資料請關注我們其它相關文章!