1. 程式人生 > >python入門學習:9.檔案和異常

python入門學習:9.檔案和異常

python入門學習:9.檔案和異常

關鍵點:檔案、異常

9.1 從檔案中讀取資料9.2 寫入檔案9.3 異常9.4 儲存資料

9.1 從檔案中讀取資料

9.1.1 讀取整個檔案
  首先建立一個pi_digits.txt檔案,內容任意填寫,儲存在當前目錄下。

1with open('pi_digits.txt'as file_object: #在當前目錄下查詢pi_digits.txt,同時返回一個檔案物件
2    contents = file_object.read()
3
    print(contents)
4
53.1415926535
6  8979323846
7  2643383279
8
9------------------

  第一句程式碼中關鍵字with,表示在不需要訪問檔案後將其自動關閉。通過情況下open()一個檔案後,需要close()關閉它。這裡使用with,在程式結束後自動關閉。
  open('pi_digits.txt')返回一個pi_digits.txt的物件,通過該物件可以操作read函式。
  可以看到列印結果有很多空格,因為read到末尾時返回一個空字串,而將空字串顯示出來就是一個空行。要刪除末尾空行,可在print語句中使用rstrip():

1with open('pi_digits.txt') as file_object: 
2    contents = file_object.read()
3    print(contents.rstrip())
4
53.1415926535
6  8979323846
7  2643383279
8------------------

9.1.2 檔案路徑
  當呼叫open()函式時,可以指定檔案路徑,預設在當前目錄下查詢。例如當前目錄/text_files/filename.txt(相對路徑)

1#linux or mac
2with open('text_files/filename.txt'as file_object:
3#windows 
4with open('text_files\filename.txt'as file_object:

  你還可以將檔案在計算機中的準確位置告訴python,即全路徑或者絕對檔案路徑

1#linux or OS
2file_path ='/home/book/Learn/python_work/chapter9/text_files/filename.txt'
3with open(file_path) as file_object:
4
5#windows
6file_path ='C:\Users\ywx\Learn\python_work\chapter9\text_files\filename.txt'
7with open(file_path) as file_object:

9.1.3 逐行讀取
  讀取檔案時,常常需要檢查其中的每一行,要以每次一行的方式檢查檔案,可對檔案物件使用for迴圈:

1filename = 'pi_digits.txt'
2with open(filename) as file_object:
3    for line in file_object:
4        print(line.rstrip())

9.1.4 建立一個包含檔案各行內容的列表
  使用關鍵字with,open()返回的檔案物件只在with程式碼塊內使用。如果要在with程式碼塊外訪問檔案的內容,可在with程式碼塊內將檔案的各行儲存在一個列表中,並在with程式碼塊外使用列表:

1filename = 'pi_digits.txt'
2with open(filename) as file_object:
3    lines = file_object.readlines()   #讀取多行存取到列表lines
4
5for line in lines:
6    print(line.rstrip())

9.1.5 使用檔案的內容
  將檔案的內容讀取後就可以使用檔案的內容了。

 1filename = 'pi_digits.txt'
2with open(filename) as file_object:
3    lines = file_object.readlines()
4
5pi_string = ''
6for line in lines:
7    pi_string += line.rstrip()  #計算圓周率rstrip()刪除末尾空格
8
9print(pi_string)
10print(len(pi_string))
11
123.1415926535  8979323846  2643383279
1336

  在變數pi_string儲存的字串中,包含原來位於左邊的空格。為刪除這些空格。可使用strip()而不是rstrip()

 1filename = 'pi_digits.txt'
2with open(filename) as file_object:
3    lines = file_object.readlines()
4
5pi_string = ''
6for line in lines:
7    pi_string += line.strip() #刪除左邊空格
8
9print(pi_string)
10print(len(pi_string))
11
123.141592653589793238462643383279
1332

  注意,讀取文字檔案時,python將其中的所有文字都解讀為字串。如果讀取的是數字,並要將其作為數值使用,必須使用函式int()將其轉化為整數,使用函式float轉換為浮點數

9.2 寫入檔案

  儲存資料的最簡單方式之一是將其寫入到檔案中。
9.2.1 寫入空檔案
  要將文字寫入檔案,在呼叫open函式時需要提供另一個引數,告訴python你要寫入開啟的檔案。

1filename = 'programming.txt'
2
3with open(filename,'w'as file_object:
4    file_object.write("I love programming")

  open第二個引數'w'(可寫)。還可以指定'r'(可讀)、'a'(附加)或者和可讀可寫('r+'),如果省略了實參,python預設只讀開啟。
  如果開啟的檔案不存在,open函式將自動建立它。然而在使用'w'(寫)模式開啟檔案時應注意,如果開啟的檔案存在,python將在返回檔案物件前情況檔案。write表示寫入檔案
9.2.2 寫入多行
  函式write不會在你寫入的檔案末尾新增換行,因此如果要寫入多行,需要指定換行符。

1filename = 'programming.txt'
2
3with open(filename,'w') as file_object:
4    file_object.write("I love programming\n")
5    file_object.write("I love programming1\n")

9.2.3 附加到檔案
  如果你要給檔案新增內容,而不是覆蓋原有內容,可以以附加模式開啟。你以附加模式開啟檔案時,python不會在返回檔案物件前清空檔案,而是寫入到檔案的行都將新增到檔案末尾。

1filename = 'programming.txt'
2
3with open(filename,'a') as file_object:
4    file_object.write("I also love finding meaning in large datasets.\n")
5    file_object.write("I love creating apps can run n a browser.\n")

9.3 異常

  python使用被稱為異常的特殊物件來管理程式執行期間發生的錯誤。每當python不知所措傳送錯誤時,它都會建立一個異常物件。
9.3.1 處理ZerodivisionError異常
  下面看一個錯誤,在Traceback中指出錯誤ZeroDivisionError是一個異常物件,python無法按照你的要求做時就會建立這種物件,表明0除法異常

1print(5/0)
2Traceback (most recent call last):
3  File "chapter9.py", line 51in <module>
4    print(5/0)
5ZeroDivisionError: division by zero

9.3.2 使用try-except程式碼塊
  當你認為可能發生了錯誤時,可編寫一個try-except程式碼塊來處理可能引發的異常。你讓python嘗試執行一些程式碼,並告訴它如果這些程式碼引發了指定的異常該怎麼辦。
  處理ZeroDivisionError異常的try-except程式碼塊類似於下面這樣:
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")

9.3.3 使else程式碼塊
  通常將可能發生的錯誤程式碼放在try-except程式碼塊中可提高這個程式抵禦錯誤的能力,依賴於try程式碼塊成功執行的程式碼都應放到else程式碼塊中:

 1print("Give me two numbers ,and I'll divide them.")
2print("Enter 'q' to quit")
3
4while True:
5    first_number = input("\nFrist number:")
6    if frist_number == 'q':
7        break
8    second_number = input("\nSecond number:")
9    if second_number == 'q':
10        break
11try:
12    answer= int(frist_number )/int(second_number )
13except ZeroDivisionError:
14    print("You can't divide by zero!")
15else:
16    print(answer)

9.3.5 處理FileNotFoundError異常
  使用檔案時,一種常見的問題是找不到檔案:你要查詢的檔案可能在其他地方、檔名可能不正確或者這個檔案根本不存在。對於所有這些情形,都可以使用try-except程式碼塊以直觀的方式進行處理。

1filename = 'alice.txt'
2with open(filename) as f_obj:
3    contens = f_obj.read()
4
5Traceback (most recent call last):
6  File "chapter9.py", line 58in <module>
7    with open(filename) as f_obj:
8FileNotFoundError: [Errno 2No such file or directory'alice.txt'

  最後一行報告了FileNotFoundError錯誤,表示python找不到指定檔案,這個錯誤是呼叫open函數出現的,所以可以把open函式放在try程式碼塊中:

1filename = 'alice.txt'
2try:
3    with open(filename) as f_obj:
4        contens = f_obj.read()
5except FileNotFoundError:
6    msg = "Sorry,the file "+ filename + " does not exist"

9.3.6 分析文字
  split()將字串以空格符分割,並將結果儲存到列表上。下面使用split分割字串。

 1filename = 'alice.txt'
2try:
3    with open(filename) as f_obj:
4        contents = f_obj.read()
5except FileNotFoundError:
6    msg = "Sorry,the file "+ filename + " does not exist"
7    print(msg)
8else:
9    words = contents.split()
10    num_words = len(words)
11    print("The file " + filename + " has about " + str(num_words) + " words")
12
13The file alice.txt has about 29461 words

9.4 儲存資料

** 使用json.dump()和json.load()**
  模組json讓你能夠將簡單的python資料結構轉儲到檔案中,並在程式再次執行時載入檔案中的資料。

  • 使用json.dump儲存資料
      json.dump()接受兩個引數,要儲存的資料以及可用於儲存資料的檔案物件。