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\n‘, ‘wangxitong\n‘, ‘weironghan\n‘, ‘weixi\n‘, ‘tiantiankaixin‘]
weiruoyu
wangxitong
weironghan
weixi
tiantiankaixin
===================================
wangxitong
参考了其他的文章:
https://www.cnblogs.com/yun1108/p/8967334.html
https://blog.csdn.net/weixin_41656968/article/details/80205717
原文地址:https://blog.51cto.com/weiruoyu/2365854
时间: 2024-11-05 17:27:05