python中read,readline,和readlines的区别 并逐行输出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中read,readline,和readlines的区别 并逐行输出相关的知识,希望对你有一定的参考价值。

python中有神奇的三种读操作:read、readline和readlines

read() ?: 一次性读取整个文件内容。推荐使用read(size)方法,size越大运行时间越长

readline() ?:每次读取一行内容。内存不够时使用,一般不太用

readlines() ? :一次性读取整个文件内容,并按行返回到list,方便我们遍历

下面看代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import linecache

f = open("a.txt")
lines = f.read()
print lines
#for i in lines:
#    print i
#    print "==="
print (type(lines))
f.close()
print 35*"="

fr = open("a.txt")
r = fr.readline()
print(type(r))
#print r
while r:
    print r,
    r = fr.readline()
    print "rrr=",r

fr.close()

print 35*"="

frs = open("a.txt")
rls = frs.readlines()
print(type(rls))
print rls
for i in rls:
    print i,
frs.close()

# 直接输出第二行
test2 = linecache.getline("a.txt", 2)
print ""
print 35*"="
print test2

运行结果如下:

weiruoyu
wangxitong
weironghan
weixi
tiantiankaixin
<type ‘str‘>
===================================
<type ‘str‘>
weiruoyu
rrr= wangxitong

wangxitong
rrr= weironghan

weironghan
rrr= weixi

weixi
rrr= tiantiankaixin
tiantiankaixin rrr= 
===================================
<type ‘list‘>
[‘weiruoyu
‘, ‘wangxitong
‘, ‘weironghan
‘, ‘weixi
‘, ‘tiantiankaixin‘]
weiruoyu
wangxitong
weironghan
weixi
tiantiankaixin 
===================================
wangxitong

参考了其他的文章:
https://www.cnblogs.com/yun1108/p/8967334.html
https://blog.csdn.net/weixin_41656968/article/details/80205717

以上是关于python中read,readline,和readlines的区别 并逐行输出的主要内容,如果未能解决你的问题,请参考以下文章

python读写文件中read()readline()和readlines()的用法

python中read,readline和readlines的区别

python中read()readline()readlines()函数

python中readline()怎么用,还有readline和readlines,read的区别和用法

Python中read()readline()和readlines()三者间的区别和用法

python中read,readline,和readlines的区别 并逐行输出