1. 程式人生 > 實用技巧 >python基礎14-檔案、異常

python基礎14-檔案、異常

# 檔案和異常:




# 讀取檔案 --讀取所有
file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt'
# 第2個實參定義 "w" --寫入(刪除原檔案),"r" --讀取,"a" --寫入(原檔案後新增),"r+" --讀寫
with open(file,"r+") as f:  
    content1 = f.write("I love play5.\n")  # "\n" --換行
    content2 = f.read()
    print(content2)



# 讀取檔案 --按行讀取
file = '
D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt' with open(file) as f: for line in f: print(line.strip()) # 刪除首尾空格 time.sleep(2) # 讀取檔案 file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read.txt' with open(file) as f: lines = f.readlines() # 檔案讀取後以 列表顯示 pi = "" for line in
lines: pi+=line.strip() # 組合成一個新的字串 print(lines[:10] + "...") # 切片查詢 print(len(pi)) # 異常處理: # try-except:出現異常 程式還能繼續執行 try: print(5/0) except ZeroDivisionError: print("you can't divide by zero !") # ZeroDivisionError --處理分子不能為0: while True: first = input("\n number1:
") if first=="q": break # 遇到break 直接退出迴圈 second = input("number2:") if second =="q": break try: answer = int(first)/int(second) # 執行條件 except ZeroDivisionError: # 條件異常丟擲錯誤 並繼續往後執行 print("you can't divide by 0!") else: print(answer) # FileNotFoundError --處理檔案找不到 filenaem = "ali.txt" try: with open(filenaem) as f : contents = f.read() except FileNotFoundError: print("file is not fond") 案例: def count(file): try: with open(file) as f : contents = f.read() except FileNotFoundError: pass # 相當於 佔位符 # print(file +"file is not fond") else: words = contents.split(sep=",") # 以逗號分隔 num = len(words) print("the file"+ file + "has about " + str(num)+ " words.") file = 'D:/liuzhuanfang/python/Hogwartsliu/xueqiu/file_read1.txt' count(file)