Python IO
使用open打開(kāi)文件后一定要記得調(diào)用文件對(duì)象的close()方法。比如可以用try/finally語(yǔ)句來(lái)確保最后能關(guān)閉文件。 在處理日志文件的時(shí)候,常常會(huì)遇到這樣的情況:日志文件巨大,不可能一次性把整個(gè)文件讀入到內(nèi)存中進(jìn)行處理,例如需要在一臺(tái)物理內(nèi)存為 2GB 的機(jī)器上處理一個(gè) 2GB 的日志文件,我們可能希望每次只處理其中 200MB 的內(nèi)容。1.open
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
注:不能把open語(yǔ)句放在try塊里,因?yàn)楫?dāng)打開(kāi)文件出現(xiàn)異常時(shí),文件對(duì)象file_object無(wú)法執(zhí)行close()方法。2.讀文件
讀文本文件
input = open('data', 'r')
#第二個(gè)參數(shù)默認(rèn)為r
input = open('data')
讀二進(jìn)制文件
input = open('data', 'rb')
讀取所有內(nèi)容
file_object = open('thefile.txt')
try:
all_the_text = file_object.read( )
finally:
file_object.close( )
讀固定字節(jié)
file_object = open('abinfile', 'rb')
try:
while True:
chunk = file_object.read(100)
if not chunk:
break
do_something_with(chunk)
finally:
file_object.close( )
讀每行
list_of_all_the_lines = file_object.readlines( )
如果文件是文本文件,還可以直接遍歷文件對(duì)象獲取每行:for line in file_object:
process line
3.寫(xiě)文件
寫(xiě)文本文件
output = open('data', 'w')
寫(xiě)二進(jìn)制文件
output = open('data', 'wb')
追加寫(xiě)文件
output = open('data', 'w+')
寫(xiě)數(shù)據(jù)
file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )
寫(xiě)入多行
file_object.writelines(list_of_text_strings)
注意,調(diào)用writelines寫(xiě)入多行在性能上會(huì)比使用write一次性寫(xiě)入要高。
在 Python 中,內(nèi)置的 File 對(duì)象直接提供了一個(gè) readlines(sizehint) 函數(shù)來(lái)完成這樣的事情。以下面的代碼為例:file = open('test.log', 'r')
sizehint = 209715200 # 200M
position = 0
lines = file.readlines(sizehint)
while not file.tell() - position < 0:
position = file.tell()
lines = file.readlines(sizehint)
posted on 2011-03-04 16:10 草原上的駱駝 閱讀(893) 評(píng)論(0) 編輯 收藏 所屬分類(lèi): Python