man = []
other = []try:data = open('sketch.txt')for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError:passprint('man[] = ', end='')print(man)print('other[] = ', end='')print(other)data.close()
except IOError:print('the file is missing!')
man = []
other = []try:data = open('sketch.txt')for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError:passprint('man[] = ', end='')print(man)print('other[] = ', end='')print(other)data.close()
except IOError:print('the file is missing!')# 使用訪問模式w時, Python會打開指定的文件來完成寫,
# 如果文件已存在則清空現有內容,
# 如果不存在則先創建文件
out = open('man.out', 'w')
print(man, file=out)# 關閉文件,相當于刷新(flushing)
out.close()
man = []
other = []try:data = open('sketch.txt')for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError:passprint('man[] = ', end='')print(man)print('other[] = ', end='')print(other)data.close()
except IOError:print('the file is missing!')# 使用訪問模式w時, Python會打開指定的文件來完成寫,
# 如果文件已存在則清空現有內容,
# 如果不存在則先創建文件
out = open('man.out', 'w')
print(man, file=out)# 關閉文件,相當于刷新(flushing)
out.close()outother = open('man.out', 'w')
print(other, file=outother)
outother.close()
# !/usr/bin/env python
# -*- coding: utf-8 -*-
man = []
other = []try:data = open('sketch.txt')for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError:passprint('man[] = ', end='')print(man)print('other[] = ', end='')print(other)data.close()
except IOError:print('the file is missing!')try:# 使用訪問模式w時, Python會打開指定的文件來完成寫,# 如果文件已存在則清空現有內容,# 如果不存在則先創建文件out = open('man.out', 'w')print(man, file=out)# 關閉文件,相當于刷新(flushing)out.close()other_data = open('man.out', 'a')print(other, file=other_data)other_data.close()
except:print('File error')
- 這里其實還存在一個小問題,我在寫文件時,捕獲了IOError,這會不會對代碼造成影響呢?我們現在都知道在進行文件操作時需要捕獲IORError,需要關閉文件,但是,如果在print時出現一個IOError,程序會怎么處理?后面的代碼還會執行嗎?文件還會關閉嗎?答案時肯定不會的,所以我們需要新的機制,在捕獲異常時,必須有一段代碼是一定能夠執行的,不被異常捕獲而中斷。
- 用finally擴展try
# !/usr/bin/env python
# -*- coding: utf-8 -*-
man = []
other = []try:data = open('sketch.txt')for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError:passprint('man[] = ', end='')print(man)print('other[] = ', end='')print(other)data.close()
except IOError:print('the file is missing!')try:# 使用訪問模式w時, Python會打開指定的文件來完成寫,# 如果文件已存在則清空現有內容,# 如果不存在則先創建文件out = open('man.out', 'w')print(man, file=out)other_data = open('man.out', 'a')print(other, file=other_data)except IOError:print('File error')finally:# 關閉文件,相當于刷新(flushing)out.close()other_data.close()
- 在出現異常時,先執行finally代碼塊,然后才會終止程序,這樣文件就不會因為出現異常而無法關閉。finall代碼塊是一段進入try代碼塊后一定會執行的部分。
- 在這里我們直接調用的關閉方法,可是當文件不存在時,是否還能直接調用關閉呢?
- 當文件不存在時,數據文件對象并未創建,這樣就不可能再數據對象上調用close()方法,所以出現一個NameError錯誤。
- 這里會再locals()BIF返回的集合中搜索字符串data,如果找到,可以認為文件成功打開
- 這里只返回了File Error,可是我們卻并不清楚是什么導致了這個錯誤,那么我們是否可以得到具體的錯誤信息呢?
- 為異常對象給定一個名,然后作為錯誤消息的一部分
- 這里要注意err是一個異常對象,并不能和字符串相連接,故需要強制類型轉換str(err)
- 用with處理文件
- 由于處理文件時 try/except/finally非常常用,所以Python提供了一個語句來抽象出相關的一些細節。對文件使用with語句時,with可以妥善地關閉一個可能打開的數據文件,而不需要finally代碼塊
man = []
other = []try:with open('sketch.txt') as data:for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError as verr:print('Value Error: ' + str(verr))pass
except IOError as err:print('File Error: ' + str(err))try:with open('man_data.txt', 'w') as man_file:print(man, file=man_file)with open('other_data.txt', 'w') as other_file:print(other, file=other_file)
except IOError as err:print('File Error: ' + str(err))
- 數據沒有格式,完全是列表儲方式的輸出
- 怎樣格式化內容呢?存儲時格式化還是讀取時格式化?
- 讀取時再格式化當然是可以的,但這需要大量的額外邏輯,另外,如果是一個協作項目,與你對接的人怎么知道你的文件內容,該怎樣格式化呢?所以我們可能需要把數據存儲成一種更容易解析的格式
- 腌制數據
- Python提供了一個標準庫, 名為pickle,它可以保存和加載任何python數據對象,包括列表
- 一旦把某個數據“腌制”到一個文件,它將會持久存儲,可以在以后某個時間都入到另外一個程序。
- 用dump保存,用load恢復
- 使用pickle只需導入所需的模塊,處理數據的唯一要求是必須以二進制模式打開這些文件
- dump“腌制”數據
import pickleman = []
other = []try:with open('sketch.txt') as data:for each_line in data:try:(role, line_spoken) = each_line.split(':', 1)# 刪除line_spoken中不需要的空白符line_spoken = line_spoken.strip()# 如果時Man說的話,加到man列表中if role == 'Man':man.append(line_spoken)# 如果時Other Man說的話,加到other列表中elif role == 'Other Man':other.append(line_spoken)except ValueError as verr:print('Value Error: ' + str(verr))pass
except IOError as err:print('File Error: ' + str(err))try:with open('man_data.txt', 'wb') as man_file:pickle.dump(man, man_file)with open('other_data.txt', 'wb') as other_file:pickle.dump(other, other_file)
except IOError as err:print('File Error: ' + str(err))
- ????pickle的數據存儲的是個什么鬼?不用擔心,它本來就是這個樣子。python的pickle使用了一種定制的二進制格式。
- 然后嘗試把它讀出來
- 大功告成
- 使用pickle的通用文件I/O才是上策
- Python負責你的文件I/O細節,這樣你就可以重點關注你的代碼實際做什么或者需要做什么
- BULLET POINTS
“不可變類型” Python中的一些數據類型,一旦賦值,這個值就不能在改變。例如:name = 'zhangsan'? ?name = 'lisi'這兩行代碼看似修改name字符串的值,實際上name的值確實改變了,變成了lisi,但是之前的‘zhangsan’的內容并沒有改變。name變量只是從指向‘zhangsan’變成了指向‘lisi’,即name='lisi'實際是做了兩件事:1.新建了一個‘lisi’的字符串 2.name指向‘lisi’Python變量只包含數據對象的一個引用,數據對象才真正包含數據。print(value, sep=' ', end='\n', file=sys.stdout)默認地BIF會顯示到屏幕(sys.stdout),這個file參數是第四個位置參數,不過,如果想把數據輸出到屏幕以外的地方,也不必為第二個或者第三個位置的參數提供值,因為他們也有缺省值。也就是說Python是根據參數名定位參數,跟位置無關,不像其他語言那樣直接傳遞參數就行,而需要連要傳遞的參數名一起寫全。例如,print('name', end='')以‘’空串結尾,不換行。這里就把end=也寫上了。“腌制”是將數據對象保存到一個持久存儲中的過程。“解除腌制”是從持久存儲中恢復一個已保存的數據對象的過程。strip()方法可以從字符串去除不想要的空白符。finally組總會執行, 而不論try/except語句中發生什么異常。locals()BIF返回當前作用域中的變量集合。in操作符用于檢查成員關系。with語句會自動處理所有一代開文件的關閉操作,即使出現遺產個也不例外。with語句也使用as關鍵字。標準庫的pickle允許你容易而高效地將Python數據對象保存到磁盤以及從磁盤恢復。pickle.dump()將數據保存到磁盤。pickle.load()從磁盤恢復數據。
總結
以上是生活随笔為你收集整理的《Head First Python》第四章--持久存储的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。