檔案讀取
讀取模式('r')、寫入模式寫入模式('w')、附加模式附加模式('a')或讓你能夠讀取和寫入檔案的模式('r+' 如果要寫入的檔案不存在,函式open()將自動創建它,然而,以寫入('w')模式打開檔案時千萬要小心,因為如果指定的檔案已經存在,Python將在回傳檔案物件前清空該檔案 python只能將字串寫入文本檔案,要將數值資料存盤到文本檔案中,必須先使用函式str()將其轉換為字串格式,
1 # f=open('test.txt','r+') 2 # f.write('Avaya')#新內容會添加在檔案的開頭,并且會覆寫開頭原有的內容 3 # f.close() 4 5 6 7 # f=open('test.txt','w') 8 # f.write('test') #w模式下使用write,會把檔案內容清空然后在開頭寫入內容 9 # f.close() 10 11 # f=open('test.txt','w+') 12 # f.write('test1')#效果與上面一樣 13 # f.close() 14 15 # f=open('test.txt','a') 16 # f.write('Hillstone') #會在檔案末尾追加 17 # f.close() 18 19 # f=open('test.txt') 20 # print(f.closed)#closed方法會回傳一個布林值,如果是打開狀態就是fales 21 # f.close() 22 # print(f.closed) 23 24 25 # with open('test.txt')as f: #with陳述句打開的檔案將自動關閉 26 # print(f.read()) 27 # print(f.closed)View Code
例外
ZeroDivisionError例外
1 try: 2 print(5/0) 3 except ZeroDivisionError: 4 print("You can't divide by zero") 5 6 You can't divide by zeroView Code
處理FileNotFoundError例外
1 filename='alice.txt' 2 with open(filename) as f_obj: 3 contents = f_obj.read() 4 Python無法讀取不存在的檔案,因此它引發一個例外: 5 Traceback (most recent call last): 6 File "E:/untitled1/alice.py", line 2, in <module> 7 with open(filename) as f_obj: 8 FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt' 9 10 filename='alice.txt' 11 try: 12 with open(filename) as f_obj: 13 contents = f_obj.read() 14 except FileNotFoundError: 15 msg="Sorry,the file "+filename+" does not exist." 16 print(msg)View Code
失敗時一聲不吭
1 filename='alice.txt' 2 try: 3 with open(filename) as f_obj: 4 contents = f_obj.read() 5 except FileNotFoundError: 6 pass#不提示錯誤訊息 7 else: 8 # 計算檔案大致包含多少個單詞 9 words= contents.split() 10 num_words=len(words) 11 print("The file "+filename+" has about "+str(num_words)+" words.")View Code
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/91815.html
標籤:Python
