加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python四种逐行读取文件的实现方法

发布时间:2020-12-17 07:15:38 所属栏目:Python 来源:网络整理
导读:对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! 下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。 方
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧!

下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。

方法一:readline函数

<style type="text/css">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'Bitstream Vera Sans Mono'; color: #28efef; background-color: #000000} span.s1 {font-variant-ligatures: no-common-ligatures}</style>

# @param Python四种逐行读取文件内容的方法
# @author 编程之家 52php.cn|www.www.52php.cn 

#-*- coding: UTF-8 -*- 
f = open("/512pic/code.txt")             # 返回一个文件对象  
line = f.readline()             # 调用文件的 readline()方法  
while line:  
    #print line,# 在 Python 2中,后面跟 ',' 将忽略换行符  
    print(line,end = '')       # 在 Python 3中使用
    line = f.readline()
f.close()

# End www.52php.cn

优点:节省内存,不需要一次性把文件内容放入内存中

缺点:速度相对较慢

 

方法二:一次读取多行数据

代码如下:

<style type="text/css">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'Bitstream Vera Sans Mono'; color: #28efef; background-color: #000000} span.s1 {font-variant-ligatures: no-common-ligatures}</style>

# @param Python四种逐行读取文件内容的方法
# @author 编程之家 52php.cn|www.www.52php.cn 

#-*- coding: UTF-8 -*- 
f = open("/512pic/code.txt")
while 1:
    lines = f.readlines(10000)
    if not lines:
        break
    for line in lines:
        print(line)
f.close()

# End www.52php.cn

一次性读取多行,可以提升读取速度,但内存使用稍大, 可根据情况调整一次读取的行数

 

方法三:直接for循环

在Python 2.2以后,我们可以直接对一个file对象使用for循环读每行数据

代码如下:

<style type="text/css">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px 'Bitstream Vera Sans Mono'; color: #28efef; background-color: #000000} span.s1 {font-variant-ligatures: no-common-ligatures}</style>

# @param Python四种逐行读取文件内容的方法
# @author 编程之家 52php.cn|www.www.52php.cn 

#-*- coding: UTF-8 -*- 
for line in open("/512pic/code.txt"):  
    #print line,#python2 用法
    print(line)

# End www.52php.cn

 

方法四:使用fileinput模块


# @param Python四种逐行读取文件内容的方法
# @author 编程之家 52php.cn|www.www.52php.cn 

import fileinput
 
for line in fileinput.input("/512pic/code.txt"):
    print(line)

# End www.52php.cn

使用简单, 但速度较慢

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读