所謂疊代,是指不斷重複某個動作,直到這些動作都完成
按位元組處理
在while循環中,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()
執行結果:
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
可以看到,該操作對檔案中的每個字元都進行循環。這個程式運作到檔案尾部時,read方法會傳回一個空字元。
#優化代碼
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實作懶加載模式
使用read和readlines方法不帶參數時将加載檔案中所有内容,然後加載到記憶體中。
當檔案很大時,這種方法會占用太多的記憶體,甚至直接記憶體溢出,進而導緻失敗。這種情況下,我們可以考慮使用while和readline方法代替這些方法。
按行讀取檔案時,若能使用for循環,則稱之為懶加載式疊代,因為在操作過程中隻讀取實際需要的部分。
使用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循環中使用檔案對象,進而進行疊代:
#! /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() #疊代結束後要顯式關閉檔案
❤️