python文件逐行讀取四種方法


下面是四種Python逐行讀取文件內容的方法, 並分析了各種方法的優缺點及應用場景,以下代碼在python3中測試通過, python2中運行部分代碼已注釋,稍加修改即可。

方法一:readline函數

1
2
3
4
5
6
7
8
#-*- coding: UTF-8 -*- 
=  open ( "/pythontab/code.txt" )              # 返回一個文件對象  
line  =  f.readline()              # 調用文件的 readline()方法  
while  line:  
     #print line,                 # 在 Python 2中,后面跟 ',' 將忽略換行符  
     print (line, end  =  '')        # 在 Python 3中使用
     line  =  f.readline()
f.close()

優點:節省內存,不需要一次性把文件內容放入內存中

缺點:速度相對較慢

 

方法二:一次讀取多行數據

代碼如下:

1
2
3
4
5
6
7
8
9
#-*- coding: UTF-8 -*- 
=  open ( "/pythontab/code.txt" )
while  1 :
     lines  =  f.readlines( 10000 )
     if  not  lines:
         break
     for  line  in  lines:
         print (line)
f.close()

一次性讀取多行,可以提升讀取速度,但內存使用稍大, 可根據情況調整一次讀取的行數

 

方法三:直接for循環

在Python 2.2以后,我們可以直接對一個file對象使用for循環讀每行數據

代碼如下:

1
2
3
4
#-*- coding: UTF-8 -*- 
for  line  in  open ( "/pythontab/code.txt" ):  
     #print line,  #python2 用法
     print (line)

 

方法四:使用fileinput模塊

1
2
3
4
import  fileinput
   
for  line  in  fileinput. input ( "/pythontab/code.txt" ):
     print (line)

使用簡單, 但速度較慢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM