Python學習筆記 Day11 檔案和異常
阿新 • • 發佈:2018-12-21
Day 11 檔案和異常
- 從檔案讀取資料
- 一次性讀取全部檔案內容
with open('pi_digits.txt') as file_object: contents =file_object.read()
- 函式open()用於開啟檔案,引數位檔名,返回值位檔案物件;
- 關鍵字with在不需要訪問檔案後自動完成關閉工作;
- 逐行讀取
file_name = "pi_digits.txt" with open(file_name) as file_object: for line in
- 從輸出結果看,open返回的file_object應該是一個列表型別的變數;
- 關鍵字with結合open()返回的檔案物件只在with程式碼塊內可見,如需在with程式碼塊外可見,則需建立一個列表物件,用於儲存檔案各行內容並留著在with程式碼塊外使用;
with open(file_name) as file_object: lines = file_object.readlines() for line in lines: print (line.rstrip())
- 使用檔案內容
file_name = "pi_million_digits.txt" with open(file_name) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print (pi_string) print (len(pi_string))
- 一次性讀取全部檔案內容
- 寫入檔案
- with open(filename, ‘w’) as file_object:
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming!")
- open的第二個實參:
- ‘r’:只讀模式開啟
- ’w’:寫入模式開啟
- ‘a’:附加模式開啟
- ’r+‘:讀取和寫入模式開啟
- 預設以只讀方式開啟檔案。
- 異常
- python程式執行過程中發生錯誤是,會產生一個異常物件,如果編寫了處理該異常的程式碼,程式繼續執行,否則,程式將停止,並顯示一個traceback。
- try expect else 程式碼塊用於處理異常
try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide bu 0!") else: print(answer)
- 分析文字
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: #計算檔案大致包含多少個單詞 words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")
- 同時處理多個檔案:將需要處理的檔名用列表儲存
#定義計算檔案有多少個單詞的函式
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exist."
print(msg)
else:
#計算檔案大致包含多少個單詞
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " +
str(num_words) + " words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt',
'little_women.txt']
for filename in filenames:
count_words(filename)