所謂迭代礁苗,是指不斷重復某個動作,直到這些動作都完成
按字節(jié)處理
在while循環(huán)中,read方法是最常見的對文件迭代的方法
#! /usr/bin/evn python
#-*- coding:utf-8 -*-
path='./test.txt'
f_name=open(path,'w')
print('write lenght:',f_name.write('Hello'))
f_name=open(path)
c_str=f_name.read(1)
while c_str:
print('read c_str is:',c_str)
c_str=f_name.read(1)
f_name.close()
執(zhí)行結果:
write lenght: 5
read c_str is: H
read c_str is: e
read c_str is: l
read c_str is: l
read c_str is: o
可以看到,該操作對文件中的每個字符都進行循環(huán)院崇。這個程序運行到文件尾部時,read方法會返回一個空字符袍祖。
#優(yōu)化代碼
f_name=open(path)
while True:
c_str=f_name.read(1)
if not c_str:
break
print('read c_str is:',c_str)
f_name.close()
按行操做
在實際操作中底瓣,處理文件時可能需要對文件的行進行迭代,而不是單個字符蕉陋。
使用readline方法按行讀取字符:
#! /usr/bin/evn python
#-*- coding:utf-8 -*-
path='./test.txt'
f_name=open(path)
while True:
line=f_name.readline(1)
if not line:
break
print('read line is:',line)
f_name.close()
使用fileinput實現(xiàn)懶加載模式
使用read和readlines方法不帶參數(shù)時將加載文件中所有內容捐凭,然后加載到內存中。
當文件很大時凳鬓,這種方法會占用太多的內存茁肠,甚至直接內存溢出,從而導致失敗村视。這種情況下官套,我們可以考慮使用while和readline方法代替這些方法。
按行讀取文件時蚁孔,若能使用for循環(huán),則稱之為懶加載式迭代惋嚎,因為在操作過程中只讀取實際需要的部分杠氢。
使用fileinput需要導入該模塊:
#! /usr/bin/evn python
#-*- coding:utf-8 -*-
import fileinput
path='g:/test.txt'
for ine in fileinput.input(path):
print('line is:',ine)
文件迭代器
從Python2.2開始,文件對象是可迭代的另伍,這意味著可以直接在for循環(huán)中使用文件對象鼻百,從而進行迭代:
#! /usr/bin/evn python
#-*- coding:utf-8 -*-
path='g:/test.txt'
f_name=open(path)
for line in f_name:
print('line is:',line)
f_name.close() #迭代結束后要顯式關閉文件
??