成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

詳解python中的異常和文件讀寫

瀏覽:4日期:2022-06-30 15:55:08
Python異常

1、python異常的完整語法

try: # 提示用戶輸入一個整數(shù) num = int(input('輸入一個整數(shù):')) # 使用 8 除以用戶輸入的整數(shù)并且輸出 result = 8 / num print(result)except ValueError: print('請輸入正確的整數(shù)!')except Exception as result: print('未知錯誤:%s' % result)else: print('嘗試成功')finally: print('無論是否出現(xiàn)錯誤都會執(zhí)行的代碼!')print('-' * 50)

2、python異常的傳遞性

當函數(shù)/方法執(zhí)行出現(xiàn)異常,會將異常傳遞給函數(shù)/方法的調(diào)用一方,如果傳遞到主程序,仍然沒有異常處理,程序才會被終止。

# 異常的傳遞性def demo1(): return int(input('輸入整數(shù):'))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> 創(chuàng)建異常對象 - 可以使用錯誤信息字符串作為參數(shù) ex = Exception('密碼長度不夠!') # 2> 主動拋出異常 raise ex# 提示用戶輸入密碼try: print(input_password())except Exception as result: print(result)Python文件讀寫

1、讀取文件后文件指針會改變

# 1. 打開文件file = open('test.py')# 2. 讀取文件內(nèi)容text = file.read()print(text)print(len(text))print('-' * 50)text = file.read()print(text)print(len(text))# 3. 關(guān)閉文件file.close()

2、復(fù)制小文件寫法

# 1. 打開file_read = open('test.py')file_write = open('test[復(fù)件].py', 'w')# 2. 讀、寫text = file_read.read()file_write.write(text)# 3. 關(guān)閉file_read.close()file_write.close()

3、復(fù)制大文件寫法

# 1. 打開file_read = open('test.py')file_write = open('test[復(fù)件].py', 'w')# 2. 讀、寫while True: # 讀取一行內(nèi)容 text = file_read.readline() # 判斷是否讀取到內(nèi)容 if not text: break file_write.write(text)# 3. 關(guān)閉file_read.close()file_write.close()

以上就是詳解python中的異常和文件讀寫的詳細內(nèi)容,更多關(guān)于python 異常和文件讀寫的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標簽: Python 編程
相關(guān)文章: