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)

使用简单, 但速度较慢

猜你喜欢

转载自www.cnblogs.com/Kingfan1993/p/9570079.html
今日推荐